How to Increment and Decrement Column Value in Laravel 6?

  10 months ago     Views:  869  
Julius Braun
1 Follows


In this article we will share with you how to increment and decrement column value in laravel 6? you can be done it many ways in laravel. here we share with you how to increment or decrement database column value with example.

Sometimes we need to increment and decrement some database column values, like in views 1,2,3, etc.., In laravel you can don this help for laravel's increment() and decrement() functions.

Here we share some examples.

Increment column values

In this example, we will see how to increment database column value bye one. if you don't pass the second argument then it will be increased by default with one.

public function increment($id)
{
	Article::find($id)->increment('views');
	//OR
	Article::where('id', $id)->increment('views');
}

Now, if you want to increment more then one value in database given column then you should pass the second argument for a specific number in increment() function.

public function increment($id)
{
	Article::find($id)->increment('views', 5);
	//OR
	Article::where('id', $id)->increment('views', 5);
}

Decrement column values

Now, in this example, we will see how to decrement database column value help of decrement() function.

public function decrement($id)
{
	Article::find($id)->decrement('views');
	//OR
	Article::where('id', $id)->decrement('views');
}

Now, if you want to decrement more then one value in database given column then you should pass the second argument for a specific number in decrement() function.

public function decrement($id)
{
	Article::find($id)->decrement('views', 5);
	//OR
	Article::where('id', $id)->decrement('views', 5);
}

Increment Or Decrement Without Using Laravel Methods

Sometimes, we need to increment and decrement database column value without using laravel helpers() function then you can be done it also help of the following ways.

Increment column value :

public function increment($id)
{
	Article::where('id', $id)->update(['views' => \DB::raw('views + 1')]);
}

Decrement column value :

public function decrement($id)
{
	Article::where('id', $id)->update(['views' => \DB::raw('views - 1')]);
}

We hope you like this small article and it will help you a lot.


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

No Comments