How to Increment and Decrement Column Value in Laravel
Laravel 27-Nov-2020

How to Increment and Decrement Column Value in Laravel

How to increment or decrement column value in laravel. In this laravel tutorial, you will how to increment or decrement column value with example.This example tutorial also work with laravel 7.x version.

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

Increment And Decrement Column Values in Larave

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

1: 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);  

2: 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); 

3: 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')]);

This query uses laravel eloquent method where(), update() and DB::raw().

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.