Laravel Eloquent belongsto relationship returns null
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
In the world of software development, Laravel is an incredibly popular PHP framework that makes web application development more efficient. One of its key components, Eloquent, offers Object-Relational Mapping (ORM) capabilities that enable you to interact with your database in a user-friendly manner. However, you might run into issues when working with relationships and NULL return values.
To set up the example that we will discuss, let's look at two Eloquent models:
1) Post:php
class Post extends Model
{
protected $table = 'posts';
protected $fillable = ['id', 'user_id', 'product_id', 'site_id', 'link_id', 'body', 'created_at', 'updated_at'];
public function user(){
return $this->belongsTo(User::class);
}
public function product(){
return $this->belongsTo(Product::class);
}
}php
protected $table = 'products';
protected $fillable = ['id', 'user_id', 'manufacturer_id', 'shift_product_id', 'name', 'english_name',
'slug', 'text', 'spec', 'live', 'created_at', 'updated_at'];
public function posts(){
return $this->hasMany(Post::class);
}Your goal is to get the related product from a post. Let's first see what happens when you perform the following:
php
$posts = Post::get();
foreach($posts as $key){
dd($key->product);
}To use optional chaining, modify your code as follows:
php
$posts = Post::get();
foreach($posts as $key){
dd($key->product?->name); // Optional chaining checks for the product and uses its 'name' attribute if available.
}