Support the ongoing development of Laravel.io →
Eloquent
Last updated 2 years ago.
0

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

0

@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.

Last updated 5 years ago.
0

@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:

  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.
0

@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.

0
Solution

@saadsaleem187 Please call this code and attach result:

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

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

0

@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.

0

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

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

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

Your logo here?

Laravel.io

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

© 2024 Laravel.io - All rights reserved.