UPDATE ADDITIONAL COLUMNS DURING INCREMENT OPERATION
May 24, 2024 Copy Link
Laravel ships with a convenient way to increment a value using the increment method:
use App\Models\User;
User::first()->increment('votes');
Occasionally, you need to pass a second argument that may be provided to specify the amount by which the column should be incremented:
use App\Models\User;
User::first()->increment('votes', 3);
In addition, If you need to update a column after you have incremented the value, you could do this:
use App\Models\User;
$user = User::first();
$user->increment('votes', 3);
$user->update(['name' => 'Mahmoud Ramadan']);
But, Laravel provides a graceful way by passing the third argument to that method:
use App\Models\User;
User::first()->increment('votes', extra: ['name' => 'Mahmoud Ramadan']);
Previously we used the named argument to pass the third parameter without the need to pass the second one.