Reputation: 1868
I have a small fundraiser portion of my site and I need to keep adding to the total amount on every transaction and how many sponsors I get.
I have my transaction set as a POST request.
Route::post('/fundraiser/checkout', 'FundController@fundCheckout')->name('fundraiser-checkout');
In my controller I'm doing the following to increment the sponsors_received
and funding_received
.
Note the below $subscription->quantity
= the amount given. $45 * 100 = 4500 cents for stripe.
$funds = DB::table('funds')->where('cin', $cin)
->increment('funding_received', $subscription->quantity)
->increment('sponsors_received');
Want to keep adding to funding_received
total and sponsors_received
.
This actually does add to my funding received
, but fails on sponsors_received
with an odd error.
Symfony\Component\Debug\Exception\FatalThrowableError Call to a member function increment() on integer
If I remove the funding_received
query everything works fine. (Can I not use increment
twice in a query?)
$funds = DB::table('funds')->where('cin', $cin)
->increment('sponsors_received');
Is there another way I can add to funding_received
other than using increment
?
Using Laravel 6+
Upvotes: 2
Views: 54
Reputation: 44526
The increment
method from the Query Builder is basically a custom update
call that handles the increment process. And because it is an update, it returns the same result as an update
call, which is the number of updated entries. That's why you get the error:
Call to a member function increment() on integer
So you can't chain the next increment
statement because the first one returns a number (integer
) instead of a Query Builder instance. You can however do something like this:
$query = DB::table('funds')->where('cin', $cin);
$query->increment('funding_received', $subscription->quantity)
$query->increment('sponsors_received');
This will create a base query with your given condition and run each increment individually.
Upvotes: 2
Reputation: 29278
You're correct. The return type of public function increment()
is an int
https://laravel.com/api/6.x/Illuminate/Database/Eloquent/Builder.html#method_increment, so chaining calls to increment()
is not allowed.
int increment(string $column, float|int $amount = 1, array $extra = [])
Increment a column's value by a given amount.
Parameters
string$column
float|int$amount
array$extra
Return Value
int
A simple way to update this is using the save()
method:
$funds = Funds::where('cin', $cin)->firstOrFail();
$funds->funding_received += $subscription->quantity;
$funds->sponsors_received++;
$funds->save();
Note: This assumes you have a model for your funds
table.
Upvotes: 1