Search code examples
laravelobjectlaravel-bladelaravel-livewire

Attempt to read property "name" on null for object within object in Livewire


I have a database model in which a player is part of a team. In a component I load these and store them to a public property

public function mount()
{
    $this->players = Player::with('team')->get();
}

In the blade file I want to show these values

<div>
    <table>
        @foreach ($players as $player)
            <tr>
                <td>{{ $player->id }}</td>
                <td>{{ $player->firstname }} {{ $player->lastname }}</td>
                <td>{{ $player->team->name }}</td>
            </tr>
        @endforeach
    </table>
</div>

This works okay if I do this in regular Laravel. However I want to do this from Livewire and it is not working. The Id, first name and lastname are displayed correct. When I want to get the name from the team, I get an error Attempt to read property "name" on null.

When I put a dd in: @dd($player->team) I get a nice list

"id" => 12
"name" => "Liverpool"

How can I access the name from the team. And why is it not working as in regular Laravel?

Edit: The data from teams is stored in a relation. I have found a solution by accessing that data also in the attributes:

$this->players = Player::leftJoin('teams', 'team_id', '=', 'teams.id')->get();

However this does not work when I have multiple teams or so.


Solution

  • Check the player model, it should have the team method like this

     public function team()
        {
            return $this->belongsTo(Team::class);
        }
    

    Confirm team_id column in the players table corresponding to the primary key id column of the teams table, and also check records in teams table.

    Eager loading works effectively when you define relationships between your models using methods like hasMany, belongsTo, etc., and establish the necessary foreign key relationships in your database schema.

    laravel Eloquent Relationships