我有兩個名為usersand 的模型和遷移表roles(對于遷移和模型名稱)。
這是我第一次使用boot(). 我有一個疑問:如果用戶成功注冊,那么他的角色應該roles作為管理員自動存盤在表中,為此請幫助我我正在嘗試一些不起作用的方法。
User.php
public static function boot()
{
parent::boot();
Static::updating(function (){});
// Here I am unable to figure out how to pass roles model or migration take data and how to update the values
}
create_roles_table.php
$table->string('role');
$table->unsignedInteger('user_id');
$table->foriegn('user_id')->references ('id')->on('users');
uj5u.com熱心網友回復:
許多用戶可以是“管理員”,是嗎?那么該roles表應具有以下結構。
// create_roles_table
$table->id();
$table->string('role'); // Admin, Manager, etc
$table->timestamps();
如果一個用戶只能有一個角色,那么該users表應該有一個指向該roles表的外鍵。
// create_users_table
$table->id();
// other fields
$table->foreignId('role_id')->constrained('roles', 'id'); // equivalent to $table->unsignedBigInteger('role_id'); $table->foreign('role_id')->references('id')->on('roles');
當用戶注冊時,laravel 會觸發事件Illuminate\Auth\Events\Registered。
你可以在App/Providers/EventServiceProvider課堂上聽。
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
public function boot()
{
// Will fire every time an User registers
Event::listen(function (Registered $event) {
$event->user->forceFill(['role_id' => ADMIN_ROLE_ID])->save();
});
}
}
如果您想改用用戶模型的事件,它應該如下所示:
class User extends Model
{
public static function boot()
{
parent::boot();
// Will fire everytime an User is created
static::creating(function (User $user) {
$user->forceFill(['role_id' => ADMIN_ROLE_ID])->save();
});
}
}
或booted()改為使用
class User extends Model
{
public static function booted()
{
// Will fire every time an User is created
static::creating(function ($user) {
$user->forceFill(['role_id' => ADMIN_ROLE_ID])->save();
});
}
}
如果用戶可以有多個角色,則需要單獨遷移。role_id不再需要在users桌子上。
// create_role_user_table
$table->id()
$table->foreignId('role_id')->constrained('roles', 'id');
$table->foreignId('user_id')->constrained('users', 'id');
然后你需要在User和Role模型中定義一個關系
// User
public function roles()
{
return $this->belongsToMany(Role::class);
}
// Role
public function users()
{
return $this->belongsToMany(User::class);
}
至于在創建/注冊用戶時更新角色用戶,替換
user->forceFill(['role_id' => ADMIN_ROLE_ID])->save()
經過
user->roles()->attach(ADMIN_ROLE_ID);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/317437.html
