laraveleager-loadingaccessormutators

Clarification with eager loading/mutators/accessors for laravel


I'm making a laravel app for work and I need to load all users with their attached role without any nesting of the roles. I used this tutorial for roles: https://medium.com/@ezp127/laravel-5-4-native-user-authentication-role-authorization-3dbae4049c8a . If I use public $with = ['roles']; on my User model it returns the entire role object within the user object and I need it to just return role:'role_name';

 /**
 * set up eloquent between roles/user
 *
 * @return \Illuminate\Database\Eloquent\Relations\belongsToMany
 */
public function roles() 
{
    return $this->belongsToMany(Role::class);
}

Above is in my User model and below is in my Role model to define the relationships.

 /**
 * provides a many-to-many relationship to User model
 *
 * @return User::class
 */
public function users()
{
  return $this->belongsToMany(User::class);
}

I thought that by adding this to the User model:

protected $appends = ['role_name'];

public function getRoleNameAttribute()
{
    return $this->attribute['name'];
}

it would return everything but all it does is create a role_name: 'user_name'; On the model. So I guess I realize I'm accessing just the Users table and not the Roles table in the DB, but again not really sure what to do. Any help would be greatly appreciated.


Solution

  • If for the purpose of convenience you need to access the role name directly from the model you should refer to the actual relationship data:

    protected $appends = ['role_name'];
    
    public function getRoleNameAttribute()
    {
        return $this->roles->pluck('name');
    }
    

    This should append the array of role names to your user model. It will be an array because roles seem to have a many-to-many relationship with the User model.