jeudi 9 février 2017

Using where() on variable result from Laravel 5 Query Builder

I have a database structure like this (to simplify):

pets table
- id
- name
- owner_id

owners table
- id
- name
- city_id

cities table
- id
- name

I'd like to print the full list of cities with, next to each one of them, the number of pets who live there. This is how I was trying to approach this problem:
This is my controller function:

// get all pets and associate them with the matching owner record, so every pet has also a city where it lives in.
$pets = DB::table('pets')->join('owners', 'pets.owner_id', '=', 'owners.id')->get();

// get all cities
$cities = DB::table('cities')->get();

// pass values to the view
return View('cities_stats',array('pets'=>$pets, 'cities'=>$cities));

On my Blade template:

@foreach($cities as $city)
    <li>
        : // city name
         pets // number of pets in this city
    </li>
@endforeach

The problem is that it of course throws an error. I cannot use neither where() nor count() in because $pets is an array.
What can I do then?

P.S. I'm using Laravel 5.0.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2kR7WGc
via IFTTT

Aucun commentaire:

Enregistrer un commentaire