【问题标题】:How to assign a role in Laravel's default AuthController如何在 Laravel 的默认 AuthController 中分配角色
【发布时间】:2016-10-20 14:19:00
【问题描述】:

我想在注册 Laravel 5.2 默认 AuthController 时为用户分配一个角色,那么如果有人知道该怎么做呢? 这里我有三个表 usersrolesuser_roles 谢谢

我的迁移: users_migration:

public function up()
{
   Schema::create('users', function (Blueprint $table) {
     $table->increments('id');
     $table->string('name');
     $table->string('email')->unique();
     $table->string('password', 60);
     $table->rememberToken();
     $table->timestamps();
  });
}

用户角色:

public function up()
{
   Schema::create('user_roles', function (Blueprint $table) {
     $table->increments('id');
     $table->integer('user_id');
     $table->integer('role_id');
     $table->timestamps();
   });
}

角色迁移:

 public function up()
{
   Schema::create('roles', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name', 60);
    $table->text('description');
    $table->timestamps();
   });
 }

还有模特:

用户模型:

  .
  .
  .
public function roles()
{
    return $this->belongsToMany('App\Role', 'user_roles','user_id','role_id');
}

榜样:

class Role extends Model
   {
      protected $primaryKey = 'r_id';

     public function users()
   {
       return $this->belongsToMany('App\User',    'user_roles','role_id','user_id');
   }
}

【问题讨论】:

    标签: php laravel-5.2 user-roles


    【解决方案1】:

    这是我所做的,但您可以随意更改。

    我将覆盖 AuthController 中 registerUsers 特征的 register()

    public function register(Request $request)
    {
      //your logic
    
      $roles = $request->input('role_id');
    
      $method = $roles instanceof Role ? 'save' : 'saveMany';
      //you can use foreach too
      $user->roles()->$method($roles);
    
    }
    

    如文档中所述,您可以使用 $user->roles()->attach($roleId) 将角色附加到用户

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-05
      • 2015-08-22
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多