Hi dev’s, Today in this Example, we will know about how to increment a value and also decrement column value in our Laravel application. So here we will use laravel eloquent increment() for increase our value and we will use laravel eloquent decrement() for decrease our value of database table.Here we will about Increment or decrement column value In Laravel.
It’s very easy method to increment value in column from table some example as bellow here.
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 8 application.
Example 2:
User::find($id)->increment('visitors');
If we ant to increment 2 then we can use increment() function in argument set 2.
Example 3:
User::find($id)->increment('visitors',2);
Decrement Example
Same as increment we can also use decrement function to decrement a column value in Laravel.
Example 1:
User::find($id)->decrement('visitors');
If you want decrement 2 then you can use decrement() function in argument set 2.
Example 2:
User::find($id)->decrement('visitors',2);
You can also use this on 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 using 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')]);
Read Also : How to check request is ajax or not in Laravel 8 ?
Thanks for read. I hope it help you. For more you can follow us on facebook