Cannot use hasMany relationship on for loop in view (Laravel)










0















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 = AppLocation::find(2);
$loc->favorites()->get()->count();


How do I get over the "array" issue on the view? Thanks in advance










share|improve this question
























  • how you get $Locations_List variable, show your controller code please. And also , you should not call get() inside loop, use EagerLoading instead

    – Zuko
    Nov 10 '18 at 19:42











  • The most important part of your code is missing from your question so it's really difficult for anyone to help you out here. The error is telling you $Locations_List is an array and that it cannot call the function favourites() 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
    Nov 10 '18 at 19:53












  • Thanks! I actually didn't think of the way I'm passing $Locations_List as being the potential issue. I was indeed passing as array and I've edited as shown above. Please see above the edited text for the controller code and updated error I'm getting.

    – SofiaP
    Nov 10 '18 at 20:30















0















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 = AppLocation::find(2);
$loc->favorites()->get()->count();


How do I get over the "array" issue on the view? Thanks in advance










share|improve this question
























  • how you get $Locations_List variable, show your controller code please. And also , you should not call get() inside loop, use EagerLoading instead

    – Zuko
    Nov 10 '18 at 19:42











  • The most important part of your code is missing from your question so it's really difficult for anyone to help you out here. The error is telling you $Locations_List is an array and that it cannot call the function favourites() 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
    Nov 10 '18 at 19:53












  • Thanks! I actually didn't think of the way I'm passing $Locations_List as being the potential issue. I was indeed passing as array and I've edited as shown above. Please see above the edited text for the controller code and updated error I'm getting.

    – SofiaP
    Nov 10 '18 at 20:30













0












0








0








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 = AppLocation::find(2);
$loc->favorites()->get()->count();


How do I get over the "array" issue on the view? Thanks in advance










share|improve this question
















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 = AppLocation::find(2);
$loc->favorites()->get()->count();


How do I get over the "array" issue on the view? Thanks in advance







php laravel has-many






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 '18 at 20:29







SofiaP

















asked Nov 10 '18 at 19:32









SofiaPSofiaP

113




113












  • how you get $Locations_List variable, show your controller code please. And also , you should not call get() inside loop, use EagerLoading instead

    – Zuko
    Nov 10 '18 at 19:42











  • The most important part of your code is missing from your question so it's really difficult for anyone to help you out here. The error is telling you $Locations_List is an array and that it cannot call the function favourites() 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
    Nov 10 '18 at 19:53












  • Thanks! I actually didn't think of the way I'm passing $Locations_List as being the potential issue. I was indeed passing as array and I've edited as shown above. Please see above the edited text for the controller code and updated error I'm getting.

    – SofiaP
    Nov 10 '18 at 20:30

















  • how you get $Locations_List variable, show your controller code please. And also , you should not call get() inside loop, use EagerLoading instead

    – Zuko
    Nov 10 '18 at 19:42











  • The most important part of your code is missing from your question so it's really difficult for anyone to help you out here. The error is telling you $Locations_List is an array and that it cannot call the function favourites() 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
    Nov 10 '18 at 19:53












  • Thanks! I actually didn't think of the way I'm passing $Locations_List as being the potential issue. I was indeed passing as array and I've edited as shown above. Please see above the edited text for the controller code and updated error I'm getting.

    – SofiaP
    Nov 10 '18 at 20:30
















how you get $Locations_List variable, show your controller code please. And also , you should not call get() inside loop, use EagerLoading instead

– Zuko
Nov 10 '18 at 19:42





how you get $Locations_List variable, show your controller code please. And also , you should not call get() inside loop, use EagerLoading instead

– Zuko
Nov 10 '18 at 19:42













The most important part of your code is missing from your question so it's really difficult for anyone to help you out here. The error is telling you $Locations_List is an array and that it cannot call the function favourites() 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
Nov 10 '18 at 19:53






The most important part of your code is missing from your question so it's really difficult for anyone to help you out here. The error is telling you $Locations_List is an array and that it cannot call the function favourites() 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
Nov 10 '18 at 19:53














Thanks! I actually didn't think of the way I'm passing $Locations_List as being the potential issue. I was indeed passing as array and I've edited as shown above. Please see above the edited text for the controller code and updated error I'm getting.

– SofiaP
Nov 10 '18 at 20:30





Thanks! I actually didn't think of the way I'm passing $Locations_List as being the potential issue. I was indeed passing as array and I've edited as shown above. Please see above the edited text for the controller code and updated error I'm getting.

– SofiaP
Nov 10 '18 at 20:30












1 Answer
1






active

oldest

votes


















-1














Try $Location->favorites->count() inside the foreach loop.



Alternatively, you can eager load the counts in the controller by adding



->withCount('favorites') when initializing $Locations_List:



$Locations_List = Location::select('id', 'Name', 'Category', 'Logo', 'Status', 'Address_Number', 'Address_Street', 'Address_City', 'Updated_At')
->withCount('favorites')
->where('Status', '>=', 500)
->get();


In this case, you can simply put $Location->favorites_count in the foreach loop.






share|improve this answer

























  • It worked! Thanks so much!!

    – SofiaP
    Nov 10 '18 at 20:56










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53242675%2fcannot-use-hasmany-relationship-on-for-loop-in-view-laravel%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









-1














Try $Location->favorites->count() inside the foreach loop.



Alternatively, you can eager load the counts in the controller by adding



->withCount('favorites') when initializing $Locations_List:



$Locations_List = Location::select('id', 'Name', 'Category', 'Logo', 'Status', 'Address_Number', 'Address_Street', 'Address_City', 'Updated_At')
->withCount('favorites')
->where('Status', '>=', 500)
->get();


In this case, you can simply put $Location->favorites_count in the foreach loop.






share|improve this answer

























  • It worked! Thanks so much!!

    – SofiaP
    Nov 10 '18 at 20:56















-1














Try $Location->favorites->count() inside the foreach loop.



Alternatively, you can eager load the counts in the controller by adding



->withCount('favorites') when initializing $Locations_List:



$Locations_List = Location::select('id', 'Name', 'Category', 'Logo', 'Status', 'Address_Number', 'Address_Street', 'Address_City', 'Updated_At')
->withCount('favorites')
->where('Status', '>=', 500)
->get();


In this case, you can simply put $Location->favorites_count in the foreach loop.






share|improve this answer

























  • It worked! Thanks so much!!

    – SofiaP
    Nov 10 '18 at 20:56













-1












-1








-1







Try $Location->favorites->count() inside the foreach loop.



Alternatively, you can eager load the counts in the controller by adding



->withCount('favorites') when initializing $Locations_List:



$Locations_List = Location::select('id', 'Name', 'Category', 'Logo', 'Status', 'Address_Number', 'Address_Street', 'Address_City', 'Updated_At')
->withCount('favorites')
->where('Status', '>=', 500)
->get();


In this case, you can simply put $Location->favorites_count in the foreach loop.






share|improve this answer















Try $Location->favorites->count() inside the foreach loop.



Alternatively, you can eager load the counts in the controller by adding



->withCount('favorites') when initializing $Locations_List:



$Locations_List = Location::select('id', 'Name', 'Category', 'Logo', 'Status', 'Address_Number', 'Address_Street', 'Address_City', 'Updated_At')
->withCount('favorites')
->where('Status', '>=', 500)
->get();


In this case, you can simply put $Location->favorites_count in the foreach loop.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 10 '18 at 20:53

























answered Nov 10 '18 at 20:33









Daniel ChenDaniel Chen

446




446












  • It worked! Thanks so much!!

    – SofiaP
    Nov 10 '18 at 20:56

















  • It worked! Thanks so much!!

    – SofiaP
    Nov 10 '18 at 20:56
















It worked! Thanks so much!!

– SofiaP
Nov 10 '18 at 20:56





It worked! Thanks so much!!

– SofiaP
Nov 10 '18 at 20:56

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53242675%2fcannot-use-hasmany-relationship-on-for-loop-in-view-laravel%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế