I am trying to code an app which has several "Locations" which users can add as their favorites. I have a model for Locations, a model for Favorites and a database table where I log pairs of user_id and location_id to indicate a user's favorite locations.
In my Location model I have defined the following hasMany relationship:
public function favorites(){
return $this->hasMany(Favorite::class);
}
I have also defined the inverse relationship on the Favorite model as follows:
public function location(){
return $this->belongsTo(Location::class);
}
Then in a view I'm trying to get a list of all locations and mark those which the user has marked as favorite. To do this I am looping through all locations, and trying to get a count on how many favorites the location has. It should be either 1 or 0, since the user_id/location_id combination row only exists if the user has the specific location as hi favorite.
Here is the relevant part of the code (I am passing a list of locations to the view):
@foreach ($Locations_List as $Location)
{{ $Location->favorites()->get()->count }}
@endforeach
Here is how I'm passing the $Locations_List:
public function Create_SearchResults(){
$Locations_List = Location::select('id', 'Name', 'Category', 'Logo', 'Status', 'Address_Number', 'Address_Street', 'Address_City', 'Updated_At')
->where('Status', '>=', 500)
->get();
return view('Location_Search/Index', compact('Locations_List'));
}
However, when I try the above, I get "Property [count] does not exist on this collection instance.".
I have tried doing something similar to the above in tinker, and it does work. However, I had to resolve the "array" piece of it as follows:
$loc = App\Location::find(2);
$loc->favorites()->get()->count();
How do I get over the "array" issue on the view? Thanks in advance
$Locations_List
variable, show your controller code please. And also , you should not call get() inside loop, use EagerLoading instead – Zuko$Locations_List
is an array and that it cannot call the functionfavourites()
on an array, which is correct. This should immediately trigger your mind with, wait, why is it an array? It's supposed to be a collection of models. So, as @Zuko said, please share where you are defining$Locations_List
and we'll more than likely immediately see what's causing the issue. – Stephen Lake