Reputation: 397
I am developing a Laravel Application for poultry farm management.
And here I am using eloquent to return a collection of Stockegg table, which stores data about the egg stock.
But as total stock is not present in the Stockegg table, I am calculating it in a loop using the initial value of the total stock.
Here is the controller:
$stockeggs = \App\Stockegg::where('farm_id', '=', $farm)->orderBy('date', 'asc')->get();
$current_stock = $initial_stock;
foreach($stockeggs as $stockegg){
$current_stock = $current_stock + $stockegg->daily_balance;
$stockegg->put('total_stock', $current_stock);
}
But I get this error:
(1/1) BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::put()
I have included the following line at the top of mu controller:
use Illuminate\Support\Collection;
Upvotes: 1
Views: 7626
Reputation: 21681
I think you should try this:
$stockeggs = \App\Stockegg::where('farm_id', '=', $farm)->orderBy('date', 'asc')->get();
$current_stock = $initial_stock;
foreach($stockeggs as $stockegg){
$current_stock = $current_stock + $stockegg->daily_balance;
//Update total stock in stockegg table
\App\Stockegg::where('id', '=', $stockegg->id)->update(array('total_stock'=>$current_stock));
}
Upvotes: 1
Reputation: 2333
You have a collection which cotains Stockegg
models so when you loop the collection, you have a single model which doesn't implement put()
method.
So let's just add total_stock
as attribute:
$stockeggs = \App\Stockegg::where('farm_id', '=', $farm)->orderBy('date', 'asc')->get();
$current_stock = $initial_stock;
foreach($stockeggs as $stockegg){
$current_stock = $current_stock + $stockegg->daily_balance;
$stockegg->total_stock= $current_stock;
$stockegg->update()
}
Upvotes: 2
Reputation: 1672
put
is not method for Eloquent. You should write code something like this.
foreach($stockeggs as $stockegg){
$current_stock = $current_stock + $stockegg->daily_balance;
$stockegg->total_stock = $current_stock;
$stockegg->save();
}
For more info https://laravel.com/docs/5.4/eloquent#updates
Upvotes: 0