Laravel 6 - increment or decrement column value example

Laravel 6 , Laravel

Nicesnippets

3706

23-09-2019


Hi dev,

In this Example, I will show you increment and decrement column value in Laravel 6. we will use laravel eloquent increment() for increase value and we will use laravel 6 eloquent decrement() for decrease value of database table.

Its Easy method to increment value in column from table example as bellow.

Increment Example

Example 1:

$user = User::find($id);

$visitors = $user->visitors + 1;

$user->update(['visitors' => $visitors]);

In this example use increment() function to increment column value in Lravel 6.

Example 2:

User::find($id)->increment('visitors');

If you increment 2 then user increment() function in argument set 2.

Example 3:

User::find($id)->increment('visitors',2);

Decrement Example

Same as increment you can use decrement function to decrement a column value in Laravel.

Example 1:

User::find($id)->decrement('visitors');

If you decrement 2 then user decrement() function in argument set 2.

Example 2:

User::find($id)->decrement('visitors',2);

You can also use DB query builder that also provides to increment and decrement a column value.

Example 1:

DB::table('users')->increment('visitors');

Example 2:

DB::table('users')->decrement('visitors');

You can also achieve this by update query.

Example 1:

User::where('id', $id)->update(['visitors' => DB::raw('visitors + 1')]);

Example 2:

User::where('id', $id)->update(['visitors' => DB::raw('visitors - 1')]);

It will help you....


Recommended Posts