2016-06-19 11 views
0

Laravel 5.2のデフォルトのAuthControllerでサインアップするときにユーザーに役割を割り当てたいので、どうすればいいですか? は、ここで私は3つのテーブルを持っているユーザー役割user_roles おかげ LaravelのデフォルトのAuthControllerで役割を割り当てる方法

マイ移行

: 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(); 
    }); 
} 

USER_ROLE:

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

とモデル:

Userモデル:

. 
    . 
    . 
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'); 
    } 
} 

答えて

0

ここでは、私は何をすべきかですが、あなたが望むものは何でもそれを変更することができます。

AuthControllerのregisterUsers特性のregister()を上書きします。ユーザー

に役割を添付する $user->roles()->attach($roleId)を使用することができますドキュメントで述べたように

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

} 

関連する問題