I have two models with relationship: City and Events.
In the controller i have this:
$cities = City::all();
return View::make('eventsdetails', compact('cities'));
In the view i have this:
@foeach($cities as $city) {{ $city->name." Events: ".$city->Events()->count(); }} @endforeach
It works!! My problem is when i need to add "wheres" in the count(). Eg:
if($categorie->id > 0){ $city->Events() ->whereCategorie($categorie->id) ->count(); }
if($subcategorie->id > 0){ $city->Events() ->whereCategorie($categorie->id) ->whereSubcategorie($subcategorie->id) ->count(); }
I don't want to use this kind of queries in my view.
What is the best way to do that??
Use the $appends attribute.
http://laravel.com/docs/eloquent#converting-to-arrays-or-json
See the link and scroll down up to the bottom page to see how it works.
Basically, what this thing does is it creates a custom attribute to your model. You will create a getter for that attribute and put the logic there. Then in your view, you can just fetch the attribute.
Other answers other than this is welcome. I'm also interested if there are other ways to do it besides this.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community