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

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

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

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

Laravel's mutators and accessors provide a convenient way to format data before it is serialized or accessed, but they come with strict typing requirements that can trip up even seasoned developers. The error Return value must be of type ?Illuminate\Database\Query\Builder, App\Models\Country returned indicates a mismatch between what your method signature promises and what the code actually executes.

In your specific case, you are attempting to access a foreign database connection within a model mutator. While the logic is sound—fetching a related Country record based on an ID—the implementation violates how Eloquent handles eager loading versus manual queries inside getters. The root cause lies in the interaction between the return type hint and the method's execution flow, but there is a deeper architectural pattern you should consider to resolve this cleanly.

The Return Type Mismatch

The error message explicitly states that your getCountryIdAttribute method is declared to return ?Builder|null, yet it returns an instance of App\Models\Country.

When you execute $country->get(), the Eloquent query builder resolves the relationship and instantiates the model. Consequently, the variable holds a Country object, not a QueryBuilder instance. Even though you are accessing the result via a chain that starts with a Builder, the final value is the hydrated model.

If you intended to return a raw array or a specific format, the method signature needs to reflect that. However, if your goal is to simply attach the related Country data to the user object (likely for JSON serialization), returning the model instance directly is actually the correct behavior. The error persists because the type hint on line 2 of your snippet claims the function returns a Builder or null, but the function body returns a Model.

To fix this specific error without changing your logic, update the return type:

public function getCountryIdAttribute(): ?Country
{
    $country = Country::where('id', $this->attributes['country_id'])
        ->getConnectionByName('my second db connection name') // Explicitly ensure connection usage
        ->first();

    return $country;
}

However, relying on manual queries inside mutators for complex relationships often leads to performance bottlenecks and "N+1" query issues if not handled carefully.

Architectural Alternatives

The most robust solution in Laravel is to define the relationship directly in the User model using the $hasOne, $belongsTo, or $belongsToMany methods, rather than implementing custom getters for every foreign key lookup.

If the Country table exists in a separate database connection, you can configure the relationship to use that specific connection:

use Illuminate\Database\Eloquent\Relations\Relation;

class User extends Model
{
    public function country(): ?Country
    {
        return new Relation(
            Country::class, 
            'id', // foreign key on user table
            'id', // local key on countries table
            ['connection' => 'my second db connection name'] // Explicitly set connection
        );
    }
}

Alternatively, if you are using Laravel 8 or later, you can leverage the getConnectionName property or pass the connection explicitly via the query builder's withConnections feature. However, a cleaner approach is to ensure the model configuration aligns with the connection name used in the query. If your Country model already specifies protected $connection = 'my second db connection name';, you can simplify the relationship definition significantly:

public function country(): ?Country
{
    return Country::where('id', $this->country_id)->first();
}

Wait—Laravel relationships are typically defined to return a Relation instance, not a Model directly. If you want to fetch the data immediately upon access, you should stick to the mutator pattern but ensure the return type matches the actual object being returned.

Handling Multiple Database Connections

Since you mentioned an external database, ensuring the query respects that connection is vital. In your Country model, you correctly set:

protected $connection = 'my second db connection name';

This ensures that any call to Country::find() or Country::where() automatically targets the correct database. When querying from within a mutator on a different model (like User), Laravel does not automatically inherit the User model's connection for the Country query. You must ensure the Country model's connection setting is respected, which it should be by default if the model class is correctly instantiated.

If you encounter issues where the query still hits the default database, verify that the connection name defined in your .env file matches exactly what is referenced in the model. Also, ensure that the my second db connection name key exists in your configuration array under database.connections.

Best Practices for Mutators

While mutators are powerful, overusing them to define entire relationships can obscure the data structure. If you find yourself frequently accessing related data via custom getters, consider using accessors and mutators only for formatting (e.g., converting a timestamp to a human-readable string) or for attaching complex nested structures that require multiple queries.

For simple one-to-one relationships like a User having a single Country, defining the relationship in the model and letting Eloquent handle the eager loading is usually preferred. For example:

$user->load('country');

This approach keeps your code declarative and leverages Laravel's query optimization engine, avoiding the pitfalls of manual queries inside mutators which can sometimes bypass connection scopes or eager-loading hints.

By aligning your return type hints with the actual instantiated objects and leveraging Laravel's relationship system for complex data fetching, you eliminate type errors while maintaining a clean, maintainable codebase.

Our network