Search code examples
laravel-5eloquentforeign-keys

Laravel 5.4 unable to access data through foreign key in blade


I m new to laravel, and have set up a couple of models and views etc. Anyways, what i am trying to do is, I have a users model, and a teams model. The field 'id' is foreign key for users' team_id.

The user can join any team and the team he joins, its id will be stored in user's 'team_id'.

What I am trying to do it, using the team_id field to get data from the teams model, like the team name and display it on my blade view.

Here is my code for Users model:

     protected $fillable = ['name',

        'email',
        'password',
        'date_of_birth',
        'team_id', /*references id in teams model*/
        'matches_played',
        'goals_scored',
        'preferred_position',
        'phone_number',
        'role',
        'ban_status',
        'team_captain' 
    ];



 

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

   
    public function Teams(){
        return $this->belongsTo('App\Teams', 'team_id');
    }

 
}

This is my code for teams model:

`protected $primaryKey = 'id';
protected $fillable = ['team_name', 'matches_played', 
'matches_lost', 'goals_scored', 'goals_conceded', 
'captain_name'];

public function User(){
    return $this->hasMany('App\User','id');
}

`

public function showMembers(){
    $users = User::with(array('Teams'))->get();
    return view('admin.members')->with('users', $users);
    }

`

` and this is how i am trying to show it in blade:

{{$user->team_id->team_name}}

But instead of displaying it, i keep on getting:

Trying to get property of non-object (View: D:\Code\PHP\Code\PlayOn\resources\views\admin\members.blade.php)

Any help would be appreciated!


Solution

  • There are a couple of things you are doing wrong here.

    First, to eager load a relationship, in this case, the teams' relationship, this is the way to do it:

    $users = User::with('Teams')->get();
    

    Finally, to loop through the Collection, you would need to do something like this:

    @foreach($users as $user)
        {{ $user->Teams->team_name }}
    @endforeach