Support the ongoing development of Laravel.io →
Eloquent Architecture

I found namespaces usage of Laravel models being non-orthogonal. When you create relation, namespace should be fully prefixed:

public function userRoles() {
    return $this->hasMany('Cse\Models\UserRole', 'user_id', 'id');
}

while in the same model code query builder statement fails unit test, when using fully qualified name:

    $userRoles = $this->userRoles()->with('Cse\Models\Role')->get();

with the following error:

BadMethodCallException: Call to undefined method Illuminate\Database\Query\Builder::Cse\Models\Role()

It works without fully qualified name, but that defeats usage of namespaces, probably can prodice namespace conflicts:

    $userRoles = $this->userRoles()->with('Role')->get();

I hope some of developers read this list.

Last updated 2 years ago.
0

the error displaying is clear, you don't have a METHOD called Cse\Models\Role() .

in the ->with() you have to pass the name of the method, no the namespace of the model. Like this:

$userRoles = $this->userRoles()->with('role')->get();

I think you have an method called role() or what ever you want, defining the relation with Cse\Models\Role model, same way yo have userRoles(). But I am not sure what are you doing.

Here some pseudo-code.. if you are trying to get users with roles:

class user extends eloquent{

 public function roles()
{
return $this->hasMany('Namespaces\Role','user_id');
}

}
$usersWithRoles = $this->with('roles')->get(); // you get the user and the related roles foreach(usersWithRoles as $ur)
  $ur->role_name
endforeach

next one is different result

$rolesOfTheUser = $this->roles()->orderBy('role_name')->get(); //returns the roles that the user has.
Last updated 2 years ago.
0

Yes you are right, I have method UserRole::role() and that's what's called when ->with() is executed. I just expected that ->with() can perform automatical joins on model class names, it seems I was wrong. The error is clear, however Eloquent probably can figure out that I am passing model class, not model method there. Or maybe not.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.