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.

Share via

Filed in:

Tips Query Builder
Mahmoud Ramadan

Mahmoud Ramadan

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

Most recent

  • 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

  • What is SQL Injection

    What is SQL Injection

    FREE