简体   繁体   中英

Eloquent: Api Resource - Can't retrieve an information from pivot table


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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM