KrisTemmerman
KrisTemmerman

Reputation: 55

How to display connected table data in blade view

I have 2 tables that have a many to many relation ship

Members: id, name , ...

Locations: id,location_id

Connected by a pivot table

members_location: member_id, location_id

in my Location model I have the following function

public function members(){
        return $this->belongsToMany('App\Member','location_member','location_id','member_id');
    }

LocationController.php Passes data to the blade template

    $locations = Location::All();
    return view('locations.overview',['locations' => $locations]);

So in my overview.blade.php i do the following

            @include('includes.message-block')
        <!-- get a list of locations -->
                <table class="member_overview table table-striped table-hover">
        <thead>
            <tr>
                <th>Naam</th>
                <th>Locatie</th>
                <th>Opmerking</th>
            </tr>
        </thead>
        <tbody>
        @foreach($locations as $location)
            <tr>
                <td>
                    {{$location->location_id}}
                </td>
                <td>
                    {{$location->members->id}}                      
                </td>
                <td>

                </td>
            </tr>
        @endforeach

Which returns an error.

Undefined property: Illuminate\Database\Eloquent\Collection::$id (View: ...)

If i drop id property on:

<td>
                        {{$location->members->id}}                      
                    </td>

I get an array [{"id":1,"first_name":"Sa ..}]. how can I select the first_name property from that array

tinker output when selecting one location

$location->members => Illuminate\Database\Eloquent\Collection {#658 all: [ App\Member {#664 id: 1,

Upvotes: 2

Views: 4552

Answers (1)

Rwd
Rwd

Reputation: 35170

the belongsToMany relationship will return a collect not a single instance of an eloquent object.

To overcome this issue you will either have loop through the members e.g.

foreach($location->members as $member) ...

of if you just want the first one then you could do:

$location->members->first()->id

Also, just an FYI but you're going to end up with a potentially large number of DB calls due to the n+1 issue that comes with many-to-many relationships. To overcome this you can simple add a with method in your controller i.e.

$locations = Location::with('members')->get();

NB you must use get and not all (like above) if you have any other methods in the chain.

Hope this helps!

Upvotes: 1

Related Questions