How to Increment and Decrement Value in Laravel 6

How to Increment and Decrement Value in Laravel 6

How to increment or decrement column value in laravel. This tutorial explains to you how you can easily increment or decrement column value with example.

Sometimes, we need to increment or decrement a column value by 1,2…. n.

Laravel provides two methods name increment() and decrement() that help you with increment or decrement column values in laravel.

Increment a column value Laravel

Let’s take an example for increment column value if you want to increment column value by one you can use the below function like below:

Post::find($id)->increment('views');
OR
Post::where('id',1)->increment("views");   

If you want to customize column increment value then you can pass the second argument in the increment() function like below:

Post::find($id)->increment('views', 5);
OR
Post::where('id',1)->increment("views", 5);  

Decrement a column value Laravel

The decrement function is the same as the increment function. You can use decrement function to decrement a column value in Laravel like below:

Post::find($id)->decrement('views');
OR
Post::where('id',1)->decrement("views");

If you want to customize column decrement value then you can pass the second argument in the decrement() function like below:

Post::find($id)->decrement('views', 5);
OR
Post::where('id',1)->decrement("views", 5); 

Increment Or Decrement Without Using Laravel Methods

If you want to use a custom query for increment or decrement column values in laravel. You can use the below query for that:

Increment column value by

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

Decrement column value by

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

Conclusion

In this tutorial, you have learned how to increment or decrement column values using the laravel inbuilt methods and without using the inbuilt method.

Leave a Reply

Your email address will not be published. Required fields are marked *