具有多个角色的Laravel身份验证

时间:2020-09-08 06:51:17

标签: php laravel authentication laravel-7

您好,我是laravel的初学者,我必须开发一个人力资源管理项目,并且有admin和employee两个角色。我遵循了laracast上的教程来构建角色和能力表,并且一切似乎都在进行。现在,我刚刚安装了laravel / ui软件包,我可以看到登录名和注册名对我在数据库中注册的用户都可以正常工作。我现在的问题是我不知道如何将事物连接在一起。如何检查登录用户是否为admin,以便打开管理面板。等待您的回复。这是代码; 我收到的错误:419页已过期

这是我尝试过的但不起作用

protected function authenticated(Request $request, $user)
    {
        // to admin dashboard
        if(auth()->user()->roles()->name === 'admin') {
            return redirect(route('admin'));
        }

        // to user dashboard
        else if(auth()->user()-roles()->name === 'user') {
            return redirect(route('home'));
        }

        abort(404);
    }

路线

   Route::get('/', function () {
        return view('welcome');
    });
    
    Auth::routes();
    
    Route::get('/home', 'HomeController@index')->name('home');
Route::get('/admin', 'LoginController@authenticated')->name('admin');

用户表

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

创建角色表

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('label')->nullable();
            $table->timestamps();

        });

        Schema::create('abilities', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('label')->nullable();
            $table->timestamps();

        });

        Schema::create('ability_role', function (Blueprint $table) {
            $table->primary(['role_id','ability_id']);

            $table->unsignedBigInteger('role_id');
            $table->unsignedBigInteger('ability_id');
            $table->timestamps();

            $table->foreign('role_id')
                ->references('id')
                ->on('roles')
                ->onDelete('cascade');

            $table->foreign('ability_id')
                ->references('id')
                ->on('roles')
                ->onDelete('cascade');
        });

        Schema::create('role_user', function (Blueprint $table) {
            $table->primary(['user_id','role_id']);

            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('role_id');
            $table->timestamps();

            $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');

            $table->foreign('role_id')
                ->references('id')
                ->on('roles')
                ->onDelete('cascade');

        });
    }

User.php

public function roles()
    {
        if(is_string($role))
        {
            $role = Role::whereName($role)->firstOrFail();
        }
        return $this->belongsToMany(Role::class)->withTimestamps();
    }

    public function assignRole($role)
    {
        $this->roles()->sync($role, false);
    }

    public function abilities($role)
    {
       return $this->roles->map->abilities->flatten()->pluck('name')->unique();
    }

Role.php

class Role extends Model
{
    protected $guarded = [];
    
    public function abilities()
    {
        return $this->belongsToMany(Ability::class)->withTimestamps();
    }

    public function allowTo($ability)
    {
        $this->abilities()->sync($ability,false);
    }
}

Ability.php

{
    protected $guarded = [];
    
    public function roles()
    {
        if(is_string($ability))
        {
            $ability = Ability::whereName($ability)->firstOrFail();
        }
        return $this->belongsToMany(Role::class)->withTimestamps();
    }
}

1 个答案:

答案 0 :(得分:0)

我也是laravel的初学者。最难的是学习新事物。所以我选择使用他们做得很好的东西。 要管理我正在使用的角色和权限,

"santigarcor/laratrust" 

您可以在此处了解更多信息:https://github.com/santigarcor/laratrust 您可以像这样使用它:

use Illuminate\Support\Facades\Auth;

if (Auth::user()->isAbleTo('edit-user')) {}
if (Auth::user()->hasRole('admin')) {}
if (Auth::user()->isA('guide')) {}
if (Auth::user()->isAn('admin')) {}

此软件包为santigarcor / laratrust软件包提供了一个用户界面

"icweb/trusty"

您可以在此处了解更多信息:https://github.com/icweb/laratrust-ui

所有表和数据将自动创建。

希望这对您有帮助!