Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment columns in laravel

Is there a way to increment more than one column in laravel?

Let's say:

DB::table('my_table') ->where('rowID', 1) ->increment('column1', 2) ->increment('column2', 10) ->increment('column3', 13) ->increment('column4', 5); 

But this results to:

Call to a member function increment() on integer

I just want to find an efficient way to do this using the given functions from laravel. Thanks. Any suggestions will do.

like image 277
Vainglory07 Avatar asked Apr 23 '15 07:04

Vainglory07


People also ask

How do I increment a field in laravel?

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.


2 Answers

There is no existing function to do this. You have to use update():

DB::table('my_table')    ->where('rowID', 1)    ->update([        'column1' => DB::raw('column1 + 2'),        'column2' => DB::raw('column2 + 10'),        'column3' => DB::raw('column3 + 13'),        'column4' => DB::raw('column4 + 5'),    ]); 
like image 129
lukasgeiter Avatar answered Oct 03 '22 02:10

lukasgeiter


Increments and Decrements in Laravel Eloquent Model

Add to cart option is one of the most important functions in e-commerce websites. The tricky part is getting the number of items in the cart to display on the cart icon. The predominant approach to get this done is using the increment and decrement function on Laravel. This also facilitates the addition or removal of a product from your cart. The way to implement this function is ,

$user = User::find(‘517c43667db388101e00000f’); $user->cart_count++; // $user->cart_count--; // for decrement the count $user->save() 

An alternate and easier way is,

$user = User::find($article_id); $user->increment('cart_count'); 

Also these will work:

$user->increment('cart_count');// increase one count $user->decrement('cart_count'); // decrease one count $user->increment('cart_count',10); // increase 10 count $user->decrement('cart_count',10); // decrease 10 count 
like image 36
Praveen AK Avatar answered Oct 03 '22 02:10

Praveen AK