How to increment or decrement a column value in laravel?

By Hardik Savani | February 2, 2016 | | 2793 Viewer | Category : Laravel


Share this post:

Whenever you need to increment or decrement value of column in database, then you do not need to first fetch that record and then update, so that way we will make long code and very hard code, so basically you can increment and decrement by using increment() and decrement() statment of laravel query builder.

If you want to increment or decrement opration using update() method of laravel query builder then you also do that, in following example 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')]);;

}

}