The error is Trying to get property 'beard_size' of non-object , maybe you can try
<td>{{$pirate->beardSize['beard_size']}}</td>
<td>{{$pirate->beardColor['beard_color']}}</td>
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have three tables:
pirates
--------------------
pirate_id (PK)
pirate_name varchar(200)
beard_size int
beard_color int
beard_sizes
--------------------
beard_size_id serial
beard_size varchar(100)
beard_colors
--------------------
beard_color_id serial
beard_color varchar(100)
Generated the models with php artisan and I'm trying to define the relations:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pirates extends Model
{
public $timestamps = false;
protected $primaryKey = 'pirate_id';
protected $fillable = ['pirate_name', 'beard_size', 'beard_color'];
public function beardSize()
{
return $this->belongsTo('App\BeardSizes', 'beard_size_id');
}
public function beardColor()
{
return $this->belongsTo('App\BeardColors', 'beard_color_id');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BeardSizes extends Model
{
public $timestamps = false;
protected $primaryKey = 'beard_size_id';
protected $fillable = ['beard_size'];
public function pirate()
{
return $this->hasMany('App\Pirates', 'pirate_id');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BeardColors extends Model
{
public $timestamps = false;
protected $primaryKey = 'beard_color_id';
protected $fillable = ['beard_color'];
public function pirate()
{
return $this->hasMany('App\Pirates', 'pirate_id');
}
}
The view:
<table class="table-view">
<thead>
<tr>
<th style="width: 60px;">No.</th>
<th>Name</th>
<th style="width: 160px;">Beard size</th>
<th style="width: 160px;">Beard color</th>
<th> </th>
<th> </th>
</tr>
</thead>
<tbody>
@foreach($pirates as $ind => $pirate)
<tr>
<td>{{ ($ind + 1) . '.' }}</td>
<td>{{ $pirate->pirate_name }}</td>
<td>{{ $pirate->beardSize->beard_size or '---' }}</td>
<td>{{ $pirate->beardColor->beard_color or '---' }}</td>
<td class="table-nav"><a href="update/{{$pirate->pirate_id}}">edit</a></td>
<td class="table-nav"><a href=delete/{{$pirate->pirate_id}}">delete</a></td>
</tr>
@endforeach
</tbody>
</table>
Every time I tried to display the pirate's beard size and beard color, I get the "Trying to get property 'beard_size' of non object. Did I make a mistake in defining the relations? I can't seem to find (or perhaps I just missed it) the tutorial regarding the correct definition of relation name (example: tables with two words or uppercase usage, etc)
Please or to participate in this conversation.