Eloquent:Api资源 - 无法从数据透视表中检索信息


I'm currently using Laravel 5.6, i want to create an user access control. I'm using three table : user (id, username, email, password), role (id, role, desc) and a pivot table role_user (user_id, role_id). My code is like below :

User Model

public function roles() {
    return $this->belongsToMany(Role::class);
}

Role Model :

/**
* Role Model
*/
public function users() {
    return $this->belongsToMany(User::class);
}

Api Resource :

/**
* Api Resource
*/
public function toArray($request)
{
   return [
      'id' => $this->id,
      'username' => $this->username,
      'email' => $this->email,
      'role' => $this->whenPivotLoaded('role_user', function (){
          return $this->roles->name;
      })
      ];
   }

The problem is when i want to access the role information from pivot table, the role is dissappear and i got blank role information like this :

{
    "data": {
        "id": 1,
        "username": "john",
        "email": "john.doe@mail.com",
    }
}

Could anyone here to help me to solve this problem?
Thank You ~

Change $this->roles->name; to return $this->roles->name;

(don't be ashamed, took me a few minutes to notice it to

Try in your controller function that is return this resource:

$user = User::where('id', '=', $id)->with('roles')->first();

and then return new UserResource($user);