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']);

 

In addition, what if we have a bunch of users and need to update them, then we may use one of these coming means:

 

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']);
});

 

FINALLY, you can forget these old traditional ways and welcome the awesome `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.

Most recent

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE

  • What is SQL Injection

    What is SQL Injection

    FREE

  • Leveraging virtual generated columns in MySQL using Laravel

    Leveraging virtual generated col...

    FREE