Laravel Increment and Decrement Column Value Example
Hey Artisan,
This extensive guide will teach you increment and decrement column in laravel. you can understand a concept of increment column value in laravel. if you want to see an example of decrement column value in laravel then you are in the right place. you can understand a concept of increment and decrement table column in laravel. follow the below step for laravel in increment and decrement column.
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....
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial