Content

          • Introduction

          • Table structure

          • Model

          • Table relationship

          • Role configuration

          • Conclusion


Introduction

Role management helps to manage authorization. Managing authorization enables us to specify the resources that users in in our application are allowed/denied to access. In Role management we can treat groups of users as a unit by assigning users to roles. After establishing roles we can create access rules in our application.

In this course I will go through how can we create a simple role management in Laravel application.

Scenario

Lets keep everything simple. In this lesson I will show you only the basics of role management. By taking this as a base idea you can upgrade it as your needs. In the following role management one user will have only one role.

Table Structure

We will have two tables: Users & Roles. The structure of the table will look like the following

Role Table

        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description');
            $table->integer('is_active');
            $table->timestamps();
        });

User table

        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name'); 
            $table->string('role_id')->unsigned();
            $table->string('phone'); 
            $table->string('password'); 
            $table->rememberToken();
            $table->timestamps();
            
            $table->foreign('role_id')->references('id')->on('roles');   
        });

As you can see above we have roles and users table. And inside users table we have role_id column which is a foreign key reference of Role’s table primary key Id. Now migrate the above table and in the consequence a table will be created in the DBMS you are using.

Read about laravel table manipulation using Eloquent ORM and about Migration here.

Models

After migration you need to create a model for these tables. Execute the following code to create a model

php artisan make:model User -m
php artisan make:model Role -m

running the above code will create User.php and Role.php file inside /app directory.

User.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    //
}
Role.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    //
}

Table Relation Using Laravel Eloquent

We have a one to one relation in between User and Role. One user has one role. To define this relationship add the following code in User.php class.

    public function role()
    {
        return $this->belongsTo('App\Role','role_id');
    }

And The following in Role.php class.

    public function users(){
        return $this->hasMany('App\User','role_id');
    }

Role Configuration

Now we have created our table and finished the relation between them. The next thing is the role configuration. We will setup the configuration inside User.php class.

    public function checkRole($roles)
        {
            
            if (is_array($roles)) {
                return $this->hasRoles($roles) ||
                        abort(401, 'This action is unauthorized.');
            }
            return $this->hasRole($roles) ||
                    abort(401, 'This action is unauthorized.');
        }

    public function hasRoles($roles)
        {  
            return in_array($this->role->name,$roles);
        }

    public function hasRole($role)
        {     
            return $this->role->name === $role;
        }

The checkRole() function takes one argument. The argument can be whether a single role or array of roles. If the argument is array of roles the hasRoles() function handles the verification. And if it is single role hasRole() functions do the checkup.

Now we have finished all the configurations and we’ve arrived at the conclusion. In the conclusion we will see How to use the role?

To check the user we will call checkRole() on the header of every controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session; 
use Illuminate\Support\Facades\Auth;


class HomeController extends Controller
{
//Allow for set of roles
 public function index(Request $request)
    {
      $request->user()->checkRole(['Manager','Customer']);   
      return view('home');
    }
//Allow for Admin only
 public function AdminIndex(Request $request)
    {
      $request->user()->checkRole('Admin');   
      return view('home');
    }
}

The index() function is allowed for a user who has a manager and a customer roles. So, if a user with admin or other roles other than the two tried to access the index() function, the checkRole() function will raise Error 401(Unauthorized Action). Also if a user with customer or manager role tried to access AdminIndex() function the same error will raise.

If the the user has no the role that we assigned for the controller the checkRole will raise Error 401(Unauthorized Action)

The following is the full code forUser.php and Role.php model.

User.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
  public function role()
    {
        return $this->belongsTo('App\Role','role_id');
    }
  public function checkRole($roles)
    {            
      if (is_array($roles)) {
      return $this->hasRoles($roles) ||abort(401, 'This action is unauthorized.');
       }
      return $this->hasRole($roles) || abort(401, 'This action is unauthorized.');
     }

    public function hasRoles($roles)
        {  
            return in_array($this->role->name,$roles);
        }

    public function hasRole($role)
        {     
            return $this->role->name === $role;
        }
}

Role.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function users(){
        return $this->hasMany('App\User','role_id');
    }
}

Conclusion

In the above lesson we have learned simple role management in laravel. Please feel free to ask any question. I’m always happy to hear from you. If you like the lesson don’t forget to share it for others.


Categories: LaravelPHPWeb

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *