How to increment or decrement a column value in Laravel?

How to increment or decrement a column value in Laravel?

In this post we will give you information about How to increment or decrement a column value in Laravel?. Hear we will give you detail about How to increment or decrement a column value in Laravel?And how to use it also give you demo for it if it is necessary.

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 IlluminateDatabaseEloquentModel;

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')]);;

}

}

Hope this code and post will helped you for implement How to increment or decrement a column value in Laravel?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

4  +  6  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US