How to Update Multiple Records in Laravel?

Hello dev, Today we are going to learn How to Update Multiple Records in Laravel? This tutorial will cover on how you can update multiple records in laravel application.

We will explained simply about how to update multiple row in laravel. we will help you to give an example of laravel update multiple records by id. You will learn laravel update multiple rows with array.

You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 versions.

If you want to update multiple rows in laravel eloquent then you can use where() with update()whereIn() with update() method of eloquent. I added three simple examples to update multiple products in laravel eloquent. so let’s see the one by one example:

Also Read: [ New ] Laravel Google 2FA Authentication Tutorial Example (2022)

Examples on Update Multiple Records in Laravel:

Example 1:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Product;
  
class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        Product::where("type", 1)
                ->update(["color" => "red"]);
  
        dd("Products updated successfully.");
    }
}

Also Read: Laravel Where Clause with Function Query Example 2022

Example 2:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Product;
  
class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $ids = [34, 56, 100, 104];
  
        Product::whereIn("id", $ids)
                ->update([
                    'color' => 'blue',
                    'size' => 'XL', 
                    'price' => 200
                ]);
  
        dd("Products updated successfully.");
    }
}

Also Read: How to Call External API in Laravel? (2022)

Example 3:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Product;
  
class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $ids = [34, 56, 100, 104];
  
        Product::whereIn("id", $ids)
                ->update($request->all());
  
        dd("Products updated successfully.");
    }
}

Conclusion

Today, We had learn How to Update Multiple Records in Laravel? Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: Laravel Eloquent addSelect() Method Example

2 Comments

Leave a Reply