Search

Increment and Decrement Column Value in Laravel

post-title

In this article we will share with you how to increment and decrement column value in laravel. 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.