2
votes

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,

1
is the location and members will have many to many relationship between each other ? - Alankar More
@AlankarMore yes they could - KrisTemmerman
I think you have mentioned the wrong table names is that typo ? "members_location" in question description and in query / relationship code you have mentioned it as " location_member" ? what is this "location_member" ? - Alankar More
@AlankarMore location member is the pivot table to connect the location and the member table - KrisTemmerman

1 Answers

1
votes

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!