Friday, December 27, 2024
Google search engine
HomeLanguagesHow to Increment and Decrement Column Value in Laravel

How to Increment and Decrement Column Value in Laravel

To increment or decrement column value in laravel. In this tutorial, you will how to increment and decrement column value in laravel 10|9|8.

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

Increment And Decrement Column Values in Laravel 10|9|8

Laravel provides two methods name increment() and decrement() that help you to increment & decrement column values in laravel 10|9|8.

  • 1: Increment a column value Laravel
  • 2: Decrement a column value Laravel
  • 3: Increment Or Decrement Column Value Without Using Laravel Methods

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 Column Value 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.

Recommended Laravel Tutorials

Recommended:-Laravel Try Catch
RELATED ARTICLES

Most Popular

Recent Comments