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