Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vivification's avatar

Call to a member function addEagerConstraints() on null

I'm trying to work out what I've done wrong, but I cannot seem to work it out.

I have the following tables;

f_account table    --> f_account_status and f_account_type   
f_account_status --> f_account_status_id 
f_account_type --> f_account_type_id 

In my AccountsController I am saying:

public function index()
    {
        $accounts = Account::with('account_type', 'account_status')->get();

        return view('accounts.index', compact('accounts'));

    }

And the Account model is:

public function account_status(){

        $this->hasOne('App\AccountStatus', 'f_account_status_id');

    }

    public function account_type(){

        $this->hasOne('App\AccountType', 'f_account_type_id');

    }

And then the type additional models,

AccountStatus

protected $table = 'f_account_status';

public function account(){

        $this->belongsTo(Account::class, 'f_account_status');

    }

AccountType

protected $table = 'f_account_type';

    public function account(){

        $this->belongsTo(Account::class, 'f_account_type');

    }

Why do I keep getting an error when trying to retrieve the results?

0 likes
5 replies
ajithlal's avatar

This error usually occurs when we are trying to call a function that can be accessed via model and accessing with empty results.

dump your results and check you are calling the method addEagerConstraints() from a null value

vivification's avatar

Thanks for the help - I've tried doing a

dd($accounts);

But it still gives me an error.

If I remove the

::with('account_type')->get();

And just have it show

$accounts = Account::all();

Then it works fine - so that suggests its a problem with the model still.

I've also just tried showing only 1 model, but still the same error applies.

ajithlal's avatar

please check the foreign key is correct on account_type function

public function account_type(){

        $this->hasOne('App\AccountType', 'f_account_type');

    }
bistrickis's avatar

You must return your relation:

public function account() {
    return $this->belongsTo(Account::class, 'f_account_status');
}
13 likes
Fajar's avatar

@vivification try this method, it worked

in youre model

public function account(){

      return  $this->belongsTo(Account::class, 'f_account_type');

    }

add return before command $this hope it can help you

Please or to participate in this conversation.