[Solved] Call to undefined relationship [department] on model [App\\Models\\User] in Laravel API

Laravel Sharif Ahmed

Problem:

Sometimes we got error Call to undefined relationship [department] on model [App\Models\User] while calling relationship method using with() on model without defining the method in model class. The exact error looks like,

Call to undefined relationship [department] on model [App\\Models\\User] in Laravel API

Solution:

With you want to include nested relationships using with(). You should use dot annotation, to declare the path of the relationship. Nested relationship loading uses .(dot) notation (relationship, other. nested, etc ). If you load a nested relationship, it loads the parent too, so you don't have to do ['company', 'employee', 'employee.department', 'employee.gradelevel']. The exact code will be,

User::with(['company', 'employee.department', 'employee.gradelevel'])->get();

See https://laravel.com/docs/8.x/eloquent-relationships#nested-eager-loading for full details.


Thank you for reading the article. Hope the given solution will solve your error.