Details
I want to
- Count all my distributors that I query
- Send it along within the JSON file
I know that I have 89 distributors in total, I did this
dd(count($distributors));I am sure what is the best practice for this.
Here is what I have tried
- I initialize
$count = 0; - Increment by 1 every time the loop execute
$count = $count + 1; - Send the result toArray
'count' => $count->toArray()as part of my distributors array
Here is my code
public function index()
{
$distributors = [];
$count = 0;
foreach(
// Specific Distributors
Distributor::where('type','!=','OEM')->where('type','!=','MKP')
->get() as $distributor){
// Variables
$count = $count + 1;
$user = $distributor->user()->first();
$distributors[$distributor->id] = [
'user' => $user->toArray(),
'distributor' => $distributor->toArray(),
'hq_country' => $distributor->country()->first(),
'address' => $distributor->addresses()
->where('type','=','Hq')->first()->toArray(),
'count' => $count->toArray()
];
}
return Response::json($distributors);
}
Result
The code won't run, due to my $distributor array is not exist ...
It will run, if I take 'count' => $count->toArray() off .
Updated
- I am using Laravel 4.0
- The code is part of my UrlController.php
$count = 0;,$count = $count + 1;, then you try to use$count->toArray()? You're treating an integer like an object.'count' => $count? Not sure why you're trying to makecountan array when it's just going to be a number. Or (if you really want it as an array)'count => array('count' => $count), but that seems quite redundant to me.countto mean to you. If you're using the aggregate count, use'count' => $counton its own. If you're trying to get the count of the query, use'count' => count($distributors)like you said yourself.data.length