Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

An Eloquent belongsTo relation is null although the parent row exists

Error$post->user is null, although the users row exists

Short answer

A belongsTo relation loads the parent whose key equals a foreign key on the child. It comes back null when that match breaks. Usual reasons: the column is not named after the relationship method, the parent's key is not id, the column is empty, the parent is soft deleted, or the relation was called with parentheses. Check the column name first.

  • Applies to Laravel 12, PHP 8.3
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Take one child row that shows null. Compare the foreign key column on it, the key it should match on the parent, and the name of the method that defines the relation. model:show prints the columns and the relations of a model.

    php artisan model:show Post
    
    # in php artisan tinker
    >>> $post = App\Models\Post::first();
    >>> $post->user_id;
    >>> $post->user;
  2. 2Match what you see, then jump to its fix

    1. 1The method is called author(), the column is user_id, and $post->author is nullThe foreign key column is not named after the relationship methodFix
    2. 2The foreign key holds a value, and the parent table is keyed by another column such as uuid or codeThe parent's key is not idFix
    3. 3$post->user_id is null, or no users row has that idThe foreign key is empty, or it points to a row that is not thereFix
    4. 4The users row exists but has a deleted_at value, and the parent model uses SoftDeletesThe parent is soft deletedFix
    5. 5The code reads $post->user()->name, or prints $post->user() and sees a relation objectThe relation is called with parenthesesFix

What does the error look like?

  • $post->user is null, although the users row exists
  • Attempt to read property "name" on null

Cause 1 of 5

The foreign key column is not named after the relationship method

1Check

Eloquent builds the default foreign key from the relationship method's name plus the parent's primary key column name. A method named user() looks for user_id on the child. A method named author() looks for author_id.

php artisan model:show Post

2Fix

Pass the real column as the second argument, or rename the method so the two agree.

public function author()
{
    // looks for posts.user_id instead of posts.author_id
    return $this->belongsTo(User::class, 'user_id');
}

3Verify

The relation returns the parent.

// in php artisan tinker
>>> App\Models\Post::first()->author?->name;

Confirmed by raw.githubusercontent.com

Did this fix it?

Cause 2 of 5

The parent's key is not id

1Check

By default the foreign key is matched against the parent's primary key. If the parent is identified by another column, the third argument of belongsTo names that owner key.

// in php artisan tinker
>>> App\Models\Post::first()->only('user_uuid');
>>> App\Models\User::first()->only('id', 'uuid');

2Fix

Give belongsTo the foreign key and the owner key, in that order.

public function user()
{
    return $this->belongsTo(User::class, 'user_uuid', 'uuid');
}

3Verify

The relation returns the parent for a row whose key is not id.

// in php artisan tinker
>>> App\Models\Post::first()->user?->name;

Confirmed by raw.githubusercontent.com

Did this fix it?

Cause 3 of 5

The foreign key is empty, or it points to a row that is not there

1Check

A null key or a key with no matching parent gives a null relation. Count both cases.

// in php artisan tinker
>>> App\Models\Post::whereNull('user_id')->count();
>>> App\Models\Post::whereNotNull('user_id')->whereNotIn('user_id', App\Models\User::select('id'))->count();

2Fix

Repair the data, and make the column required in the migration so it cannot be empty again. Where a missing parent is allowed, give the relation a default model, so reading it never returns null.

public function user()
{
    return $this->belongsTo(User::class)->withDefault();
}

3Verify

Reading $post->user for a row without a parent returns a model instead of null.

// in php artisan tinker
>>> App\Models\Post::whereNull('user_id')->first()?->user;

Confirmed by raw.githubusercontent.com

Did this fix it?

Cause 4 of 5

The parent is soft deleted

1Check

Soft deleted models are excluded from query results automatically, and the relation runs a query. A soft deleted parent therefore reads as null.

// in php artisan tinker
>>> App\Models\User::withTrashed()->find(1)?->deleted_at;

2Fix

If the child should still see its deleted parent, call withTrashed() on the relationship query.

public function user()
{
    return $this->belongsTo(User::class)->withTrashed();
}

3Verify

$post->user returns the soft deleted parent.

// in php artisan tinker
>>> App\Models\Post::first()->user?->deleted_at;

Confirmed by laravel.com

Did this fix it?

Cause 5 of 5

The relation is called with parentheses

1Check

Reading the relation as a property loads and returns the parent. Calling the method with parentheses returns the relation itself, which is a query builder, not the parent model.

grep -rnE "\->user\(\)->[a-z_]+" app/ resources/views/

2Fix

Read the property to get the model. Use the method only when you want to add constraints to the query.

// the parent model
$name = $post->user->name;

// the relation as a query
$name = $post->user()->first()?->name;

3Verify

The value is the parent's attribute, not null and not an error.

// in php artisan tinker
>>> App\Models\Post::first()->user?->name;

Confirmed by raw.githubusercontent.com

Did this fix it?

How do I stop it coming back?

  • Name the relationship method after the foreign key column, or write the column explicitly in belongsTo.
  • Declare the foreign key in the migration with a constraint, so a missing parent cannot be stored.
  • Use withDefault() where a missing parent is normal, and the nullsafe operator in code that must cope with null.
  • Run php artisan model:show on a model whenever a relation behaves oddly. It lists the columns next to the relations.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

composer require maatwebsite/excel fails to install

Composer says the package needs an older PHP than the one installed

Composer refuses maatwebsite/excel when the PHP version or a PHP extension does not match what the package and PhpSpreadsheet need.

3 causes, each with a fix

Back end

composer require laravel/horizon fails: ext-pcntl is missing

laravel/horizon v1.1.0 requires ext-pcntl * -> the requested PHP extension pcntl is missing from your system

Horizon needs the pcntl extension, and Composer refuses to install it where PHP lacks that extension.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.