Skip to content
Advertisement

Return value must be of type ?Illuminate\Database\Query\Builder, App\Models\ModelName returned

I’m trying to have the following response:

JavaScript

Instead of:

JavaScript

In order to do that, I am using a mutator function inside the User Model:

JavaScript

However, the countries table is already found in an external database which I set up its connection properly.

But I created the Country Model following this Laravel documentation:

JavaScript

When I am trying to fetch the user I get the following error:

JavaScript

I tried to explain my case as much as possible. Thank you for your help.

Advertisement

Answer

The problem is that you are saying in the function getCountryIdAttribute it returns Builder | null. When you do

JavaScript

It will return an instance of Country or null. To fix your problem you should update your return type to Country | null:

JavaScript

Laravel provides ways to work with relationships that will greatly improve your code performance. In this case you can do:

JavaScript

Then when fetching the users you can do:

JavaScript

This will prevent your code from having N+1 problems.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement