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