0

我有两个名为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');
4

1 回答 1

1

许多用户可以是“管理员”,是吗?那么该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');

然后你需要在UserRole模型中定义一个关系

// 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);
于 2021-10-14T17:47:42.880 回答