system login Laravel with permission levels

Asked

Viewed 3,524 times

-1

I’m trying to set up a login system but I can’t get the result I need.

There are three types of users:

  • Admin
  • User ()
  • Teachers ()

I adapted the make:auth with roles to create teacher and student, is working. However the admin will register both users, so only he can access a few pages.

I want to know how I can differentiate the access to the pages, for example, the registration page be accessed only by admin. I saw something of Laravel Gates Permissions etc. But I didn’t understand it very well.

I even created a field in the users table is_admin, but I don’t know what to do and how to check the pages.

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

2 answers

0

public function up()
{
    Schema::create('user', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->boolean('is_admin')->default(0);
        $table->rememberToken();
        $table->timestamps();
    });

Now just check the page

@if($user->is_admin)
 //código html etc
@endif

The best would be to create a Table of Rules

//Tabela Regra
Schema::create('role', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
});

//Tabela Regra_usuario 
Schema::create('user_role', function (Blueprint $table) {
    $table->bigInteger('user_id')->unsigned();
    $table->integer('role_id')->unsigned();
    $table->foreign('user_id')
        ->references('id')->on('user');
    $table->foreign('role_id')
        ->references('id')->on('role');
});

Now on the User_model

public function isAdministrator() {
   return $this->roles()->where('name', 'Administrator')->exists();
}

//na View
@if(Auth::user()->isAdministrator())
    // html etc
@endif

0

As I noticed, you are using the is_admin column that was provided in the example of Laravel documentation but in this case it would not be the most appropriate because its permission levels are 3 and not 2 (something that is_admin could easily handle).

I suggest you change the column to whole and check the permission based on the level:

$table->integer('permissao')->default(0);

And the check to :

@if($user->permissao == valordepermissao)
  //LIBERE ALGUMA PAGINA
@endif

Browser other questions tagged

You are not signed in. Login or sign up in order to post.