Eduardo Güereque
Eduardo Güereque

Reputation: 67

Getting related data from a collection result in Laravel

I retrieved a collection of locations by id of a Firm. One firm can have many locations. Now I'm trying to retrieve staff from a location. One location can have many staff members.

Staff model only relates with Location model.

Code is in a show function in a controller.

I thought now that I have related locations for a particular firm I can just use that collection to get staff members. However, I've hit a roadblock and help would be greatly appreciated. Thanks.

public function showFirm($id)
{
    // Get locations of a firm by id
    $firm_locations = Firm::find($id)->firmLocations;
}

Upvotes: 1

Views: 47

Answers (1)

Rutvij Kothari
Rutvij Kothari

Reputation: 1285

You can retrieve Staff based on location along with firm.

public function showFirm($id) {

    // Get locations of a firm by id with staff member from location

    $firm_locations = Firm::where('id',$id)->with('firmLocations.staff')->first();

    // Above function retrieve Firm with Location and Location will have staff.
}

I am assuming you've set up relationship correctly and you've working knowledge of relationship.

Upvotes: 1

Related Questions