Access to multilevel relationships in laravel

Viewed 121

can someone help me on getting data from multi level relationships in laravel?

I want to do something like BagageAnnouncement->Announcement->user->profile->"name of the field"

 $data = $request->text;


     $filter = BagageAnnouncement::whereHas('announcement',function ($query) {
    })->whereHas('user', function ($query) {
    })->whereHas('profile',function($query){
        $query->where('level',$data)
})->get();
2 Answers

Thank you guys for you answers I finally figure out a solution

  $data = $request->text;
    $filter = BagageAnnouncement::whereHas(
        'announcement.user.profile',
        function ($q2) use ($data) {
            $q2->where('level',$data);
        }
    )->get();

Not sure what you want as the result, but if you want a single result, you can do like this:

$bagage = BagageAnnouncement::where(specify_your_condition)->first();
$filter = $bagage->user->profile->name_of_the_field;

If you want an array of results, change the first() to get() and make use of foreach

Of course, you will need to set up the relationships in your models first.

Related