Support the ongoing development of →
Last updated 2 years ago.

How you query the second side of the relationship? (I mean command that you access cover property)


@dracola Below is my query

$magazines = MediaProfile::where('category', 'Magazines')->get();

Than i passed this $magazines variable to view and in view i access the cover property which is the field of second table like this

foreach($magazines as $magazine)
{{ $magazine->mediaProfilesContent->cover }}

Above mediaProfilesContent is my MediaProfile model method which i defined for relationship.

Last updated 6 years ago.

mediaProfilesContent is hasMany relation. It returns collection of items not item object. So you are trying to get field of object from collection of objects. Correct ways to do it depends of your business logic.

I see two ways:

  1. Change relation type to hasOne instead of hasMany. In this case you will get first object instead of collection of objects.
  2. Add for each on $magazine->mediaProfilesContent if you have many covers.

@Roman Dubrovin I changed relation type to hasOne but it gives me same error. I am not getting anything. I applied both of your methods but it didn't worked for me. Also i add below code in my controller method to test that it returns me data from mediaProfilesContent table or not.

$magazines = MediaProfile::where('category', 'Magazines')->get();
return view('magazines', ['magazines' => $magazines]);

Above code only gives me data from MediaProfile table not from second table. I need help i am stuck in this error from last week.


@saadsaleem187 Please call this code and attach result:

$magazines = MediaProfile::where('category', 'Magazines')

@Roman Dubrovin You are amazing. Its done man with your solution. I just got all my data. Thank you so much for your help.


@saadsaleem187 Just a little advice. Don't use your models in templates. This is bad practice. Divide responsibility between controllers and views. Send to views arrays instead of models and you can check states of your data more clear in any moment.


@Roman Dubrovin thanks for the advice man. From now on i will definitely follow it.


Sign in to participate in this thread!


Your banner here too?


We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 - All rights reserved.