UPDATE EXTRA COLUMNS WHEN YOU INCREMENT

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.

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 Autoloading in Versions Before v12.8

    PREMIUM

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to welcome Laravel v12

    PREMIUM

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using TCPDF

    FREE