如何让用户在laravel中扮演角色?

时间:2016-09-23 17:21:15

标签: laravel eloquent laravel-5.2

我有一个有很多关系的用户模型"很多很多"与角色模型。 用户模型:

class User extends Model
{
    ...
    public function roles()
    {
        return $this->belongsToMany(Config::get('entrust.role'), Config::get('entrust.role_user_table'), 'user_id', 'role_id');
    }
}

我有一个用户控制器,它有一个以JSON格式获取用户数据的方法:

class UserController extends Controller {
    ...

    // GET /user/3
    public function show(User $user)
    {
        // $user is a single user
        // return single user's data without roles
        // I want to get user WITH roles
        return $user;
    }

    // GET /users
    public function index(User $user)
    {
        // returns list of users with roles.
        $user->with('roles')->get();
    }
}

方法show()以JSON格式返回没有角色的用户数据。如何使用角色数据获取用户的数据?

对于用户列表(index() method),我可以使用with()方法返回具有角色的用户,但我不知道如何在show()方法中执行此操作

return dd($user)方法输出中的

show()

User {#192 ▼
  #fillable: array:7 [▼
    0 => "name"
    1 => "email"
    2 => "password"
    3 => "username"
    4 => "first_name"
    5 => "last_name"
    6 => "is_guest"
  ]
  #hidden: array:2 [▼
    0 => "password"
    1 => "remember_token"
  ]
  #totalCount: null
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:11 [▼
    "id" => 11
    "username" => "some_username6"
    "email" => "email@example.com6"
    "password" => "$2y$10$h8mN6r8rWdiXv9VJG5z7NucaOrD9kEtfBSXnL6BdJGzV1671EkdaG"
    "name" => "some name6"
    "first_name" => "some_first_name6"
    "last_name" => "some_last_name6"
    "remember_token" => null
    "created_at" => "2016-09-02 19:14:46"
    "updated_at" => "2016-09-02 19:14:46"
    "is_guest" => 1
  ]
  #original: array:11 [▼
    "id" => 11
    "username" => "some_username6"
    "email" => "email@example.com6"
    "password" => "$2y$10$h8mN6r8rWdiXv9VJG5z7NucaOrD9kEtfBSXnL6BdJGzV1671EkdaG"
    "name" => "some name6"
    "first_name" => "some_first_name6"
    "last_name" => "some_last_name6"
    "remember_token" => null
    "created_at" => "2016-09-02 19:14:46"
    "updated_at" => "2016-09-02 19:14:46"
    "is_guest" => 1
  ]
  #relations: []
  #visible: []
  #appends: []
  #guarded: array:1 [▼
    0 => "*"
  ]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: false
}

3 个答案:

答案 0 :(得分:4)

您可以在现有模型对象上使用load函数来加载关系的数据。

$user->load('roles')
return $user;

答案 1 :(得分:4)

在show方法中使用load函数:

class UserController extends Controller 
{
    public function show(User $user)
    {
        return $user->load('roles');
    }

    public function index(User $user)
    {
        return $user->with('roles')->get();
    }
}

答案 2 :(得分:-1)

你可以简单地做

User::with('role')->get();