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 }}
@endforeach
Above mediaProfilesContent is my MediaProfile model method which i defined for relationship.
@saadsaleem187
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:
@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();
dd($magazines[0]->mediaProfilesContent());
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')
->with('mediaProfilesContent')
->get()
->toArray();
@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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community