natas
natas

Reputation: 456

Retrieve relationship items from a collection

In a controller I create a collection with:

$playershome = App\Team::where('id', $session->team1_id)->with('players')->first();

and call my view with:

        return view('member.home', compact('user', 'session', 'playershome', 'playersaway'));

In my Team model I've:

    public function players(){
        return $this->belongsToMany(User::class, 'team_users');
}

The collection is created:

Team Collection

But I don't know how to retrieve "players" item in my view. I try with:

@foreach($playershome->players as $player)

But I got:

Invalid argument supplied for foreach()

What wrong?

UPDATE view:

                                            <div class="mt-body">
                                            <h3 class="mt-body-title"> {{$session->team1Id->name}} </h3>
                                            <p class="mt-body-description"> It is a long established fact that a reader will be distracted </p>
                                            <ul class="mt-body-stats">
                                                @foreach($playershome->players as $player)

                                                    <li class="font-green">
                                                        <img src="/storage/{{$player->avatar}}"></li>
                                                @endforeach
                                            </ul>
                                            <div class="mt-body-actions">
                                                <div class="btn-group btn-group btn-group-justified">
                                                    <a href="javascript:;" class="btn">
                                                        <i class="icon-bubbles"></i> Punti </a>
                                                    <a href="javascript:;" class="btn ">
                                                        <i class="icon-social-twitter"></i> K/D </a>
                                                </div>
                                            </div>
                                        </div>

Upvotes: 0

Views: 6686

Answers (2)

Teun
Teun

Reputation: 926

Looking at your chat that you had in the comments I see that you are using the same name for an attribute called players in your teams table, and also the relation to the users is called players. Try renaming the relation to something else, change it in your query and also in your foreach.

EDIT: Found stackoverflow question to the same issue as you: Laravel get Eloquent relation by same name as its attribute

Upvotes: 1

Eden WebStudio
Eden WebStudio

Reputation: 788

Try this way round

$playershome = App\Team::with('players')->where('id', $session->team1_id)->get();

Upvotes: 0

Related Questions