Laravel Increment and Decrement Column Value Example

Laravel increment or decrement column value; Through this tutorial, i am going to show you how to increment or decrement column value in laravel apps.

How to Increment And Decrement Column Values in Laravel

Let’s see the following examples of increment() and decrement() method, which is used to increment or decrement column values in laravel apps:

  • Increment a column value Laravel
  • Decrement a column value Laravel
  • Increment Or Decrement Without Using Laravel Methods

Increment a column value Laravel

To increment column value in laravel apps using the following example; as follows:

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

To decrement column value in laravel apps using the decrement() method; as follows:

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

And also you can increment and decrement column values in laravel apps using the db::raw() function in laravel apps; as follows:

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.

Recommended Laravel Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.