HOW TO UPDATE LARAVEL COLLECTION AMAZINGLY

Dec 29, 2023 Copy Link

If we need to update only one model instance using the `update` method, we will follow the next step:

 

use App\Models\User;

$user = User::first();

$user->update(['status' => 'Administrator']);

 

Additionally, if we need to update a large number of users, we can consider the following approaches:

 

1. Using a simple For Loop

 

use App\Models\User;

$users = User::where('status', 'VIP')->get();

foreach ($users as $user) {
    $user->update(['status' => 'Administrator']);
}

 

2. Using Laravel Collections

 

use App\Models\User;

$users = User::where('status', 'VIP')->get();

$users->each(function ($user) {
    $user->update(['status' => 'Administrator']);
});

 

Instead of relying on outdated approaches, consider using the elegant and efficient toQuery method:

 

use App\Models\User;

User::where('status', 'VIP')
    ->get()
    ->toQuery()
    ->update([
        'status' => 'Administrator'
    ]);

Share via

Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Newly published

  • How to Enable Relationship Autoloading in Versions Before v12.8

    How to Enable Relationship Autol...

    FREE

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to we...

    FREE

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE