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.
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);
}
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);
}
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.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Disable Text Selection In WebPage Using jQuery and CSS
Many times you need to prevent text sele...How to Find the Max and Min Values of an Array in JavaScript
Use the apply() Method You can use th...Laravel 8 Create Dummy Data using laravel/tinker Package
Today we will learn how to engender dumm...Hot to Create Bar Chart in Angular using ng2-charts
This tutorial will give you an example o...How to get the Client IP Address in PHP
When working in one of my project, I wan...