How to increment or decrement a column value in Laravel?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this tutorial i will show you how to increment or decrement a column value in laravel. When we need to increment or need to decrement value of column in database, then we do not need to first fetch that record and then update, so on that way we will make long code and very hard code, so it is basically we can increment and decrement by using increment() and decrement() statement of laravel query builder.

So If we want to increment or decrement operation by using update() method of laravel query builder and then we also do that, in following example so i am showing you how to increment and decrement value of column in table by using increment(), decrement() and update().

namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
class Item extends Model
{
    
    // plus 1 By Using increment()
    public function countIncrement($id = 1)
    {
    	static::where('id',$id)->increment('count',1);
    }
    // plus 1 By Using update()
    public function countIncrementWithUpdate($id = 1)
    {
    	static::where('id',$id)->update(['count' => DB::raw('count+1')]);;
    }
    // minus 1 By Using decrement()
    public function countDecrement($id = 1)
    {
    	static::where('id',$id)->decrement('count',1);
    }
    // minus 1 By Using update()
    public function countDecrementWithUpdate($id = 1)
    {
    	static::where('id',$id)->update(['count' => DB::raw('count-1')]);;
    }
}

Read Also : How to Open Link in New Window by using Javascript ?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →