How to Delete Multiple Records in Laravel 9 - Techvblogs

How to Delete Multiple Records in Laravel 9

Learn how to delete multiple records in Laravel 9 efficiently with this simple and practical step-by-step tutorial.


Smit Pipaliya - Author - Techvblogs
Smit Pipaliya
 

2 days ago

TechvBlogs - Google News

Hey Folks, It almost needs to remove multiple records. If you are developing e-commerce or any extensive web application, you may be provided an option to delete multiple records.

In this article, You will learn How to Delete Multiple Records in Laravel 9. Also, you can learn How to delete a single record from the database.

How to Delete Multiple Records in Laravel 9

App\Models\Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'posts';

    protected $fillable = ['title', 'banner', 'slug', 'description'];
}

app\Http\Controllers\PostController.php

You can use the destroyMultiple method and pass one or more primary keys to it as a form request.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{        
    public function destroyMultiple(Request $request){
        try {

            Post::destroy($request->ids);
            return response()->json([
                'message'=>"Posts Deleted successfully."
            ],200);

        } catch(\Exception $e) {
            report($e);
        }
    }
}

You can also use this option to remove records with a custom parameter.

Post::where('title', 'Laravel')->delete();

Also, you can use the query builder to delete multiple and single records from the database. Here is an example of Eloquent Query for deleting single or multiple records from the database in Laravel.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{        
    public function destroyMultiple(Request $request){
        try {

            DB::table('posts')->whereIn('id',$request->ids)->delete();
            return response()->json([
                'message'=>"Posts Deleted successfully."
            ],200);

        } catch(\Exception $e) {
            report($e);
        }
    }
}

Thank you for reading this blog.

Read Also: How to Get only records created today in Laravel

Comments (0)

Comment


Note: All Input Fields are required.