Reputation: 518
I don't know if I'm not holding my toungue right or something, but I'm trying to get a total in the table footer. I have no doubt there is something I'm missing, here is what I tried:
$labors = Labor::where('created_at', '>=', new DateTime('today'))->get()->sum('labor');
Which works well up until here:
->sum('labor')
Then I get:
Call to undefined method Illuminate\Database\Eloquent\Collection::sum()
So I'm obviously using it incorrectly because it's in the docs here:
http://four.laravel.com/docs/queries
Some feedback would be much appreciated. :)
I think this might actually be relevant:
public function index()
{
$labors = Labor::where('created_at', '>=', new DateTime('today'))->sum('labor');
return View::make('labors.index', compact('labors'));
}
Upvotes: 0
Views: 1100
Reputation: 87789
If you need to do a foreach, you will have to do 2 queries:
$total = Labor::where('created_at', '>=', new DateTime('today'))->sum('labor');
$labors = Labor::where('created_at', '>=', new DateTime('today'))->get();
This is because sum() returns an integer with the sum, not a collection.
Upvotes: 1
Reputation: 1075
You need to do 2 things:
$labors = Labor::where('created_at', '>=', new DateTime('today'))->get();
The above gets the array for use in the foreach.
$laborTotal = Labor::where('created_at', '>=', new DateTime('today'))->sum('labor');
That gets the total. So then is all you need to do is sent them both to the view and just use the total in the footer of the table:
return View::make('labors.index', compact('labors', 'laborTotal'));
View something like:
@foreach ($labors as $labor)
<tr> ... </tr>
@endforeach
<tr><td>{{ $laborTotal }}</td></tr>
Upvotes: 3
Reputation: 18598
Pretty sure it should be
$labors = Labor::where('created_at', '>=', new DateTime('today'))->sum('labor');
This is as per Eloquent Aggregates you were looking at the Fluent docs
You don't need to compact
$labors now though as it's a string not an array
Upvotes: 1