Is there a way to alias a Eloquent relationship when eager loading? For example, I might have a query such as the following.
User::with(['roles' => function ($query) { $query->where('type', ADMIN); }]);
But what if I also want to eager load roles with a status of ACTIVE? The only way I can think of doing it is to duplicate the roles relationship on the User model and give it a different name. The query would then look something like the following.
User::with([
'roles' => function ($query) { $query->where('type', ADMIN); },
'otherRoles' => function ($query) { $query->where('status', ACTIVE) }]
);
I could have methods such as adminRoles and activeRoles on my user model, but that's really not what I am looking for as there are so many possible parameters.
You've indicated you don't want to have additional methods on your user model, but that's the best approach you've got apart from using closures like you are already. You can improve the code a little bit by having your new methods like adminRoles leverage the existing relationship method, and a scope provided by the related model.
class User extends Eloquent
{
public function roles()
{
return $this->hasMany(Role::class);
}
public function adminRoles()
{
return $this->roles()->admin();
}
}
Then define the scopes you want to use on your Role model.
class Role extends Eloquent
{
public function scopeAdmin($query)
{
$query->where('type', static::ADMIN);
}
}
And you can now eager load these scoped relationships.
User::with('adminRoles')->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With