Wednesday, 11 May 2016

Unknown

Roles in laravel -Create roles for Securing Routes according to users in Laravel 5.2 at easyLaravel

Note : If you want to separate admin and users or customer or seller ,this tutorial is for you.

Click here to download all file of this tutorial - Download

Roles are important in web application like in blog there is admin who will create post and users who will see post and comment on them ,so in order to differentiate admin from user we use role concept.

Apply Roles to any route and hence secure routes according to roles.
Step 1: Create migration Create_Role_Table.php to create Roles table. We use artisan command -
" php artisan make:migration Create_Roles_Table --create=roles "
Once migration is created update migration file following code  -

   public function up()
    {
        Schema::create('Roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 40);
            $table->string('description', 255);
            $table->timestamps();
          
        });
    }
    public function down()
    {
        Schema::drop('Roles');
    }

Step 2: Create migration AddRoleIdUserTable.php to add foreign key roleid to user table. We use artisan command -
" php artisan make:migration AddRoleIdUserTable --table=roles "
Once migration is created update migration file following code  -

  public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            //
              $table->integer('role_id')->unsigned();
             $table->Foreign('role_id')
                     ->references('id')
                   ->on('roles')
                      ->onDelete('cascade');
        });
    }
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //
              $table->dropColumn('role_id');
        });
    }

Step 3 : Creating Role model and establishing relation with user.
Create Role model using artisan command =
" php artisan make:model Role "
Add following code in Role.php

  protected $table = 'roles';
    
    public function users()
    {
        return $this->hasMany('App\User', 'role_id', 'id');
    }
Above code says that User has many role.

Add Following code in User.php model file -
 protected $hidden = ['password', 'remember_token'];
        public function role()
    {
        return $this->hasOne('App\Role', 'id','role_id');
    }
    public function hasRole($roles)
    { 
        $this->have_role = $this->getUserRole();
        // Check if the user is a root accoun
        if($this->have_role->name == 'Root') {
            return true;
        }
        if($this->have_role->name == 'User') {
                //check if user is a USer account
               //dd($this->have_role->name);
            return true;
        }
        if(is_array($roles)){
            foreach($roles as $need_role){
                if($this->checkIfUserHasRole($need_role)) {
                    return true;
                }
            }
        } else{
            return $this->checkIfUserHasRole($roles);
        }
        return false;
    }
    private function getUserRole()
    {
        return $this->role()->getResults();
    }
    private function checkIfUserHasRole($need_role)
    {
        return (strtolower($need_role)==strtolower($this->have_role->name)) ? true : false;
    }

In above code , we establish relationship creating funtion roles() and define relation using hasOne() eloquent relationship helper that says user has one role.

Next function hasRole() checks that when user is logged in and access a route, it checks whether user has role or not.

Step 5 - Create Middleware using artisan command -
" php artisan make:middleware CheckRole "

Add Following Code in handle() method-
     public function handle($request, Closure $next)
    {
   // dd($request);
         $roles = $this->getRequiredRoleForRoute($request->route());
      // dd($roles);      
        // Check if a role is required for the route, and
        // if so, ensure that the user has that role.
         //dd($roles);
         if($roles[0]=='Guest')
         {          return $next($request);
         }
         else
         {
                if($request->user())
                {                        if($request->user()->hasRole($roles) || !$roles )
                        {
                            return $next($request);
                        }
                }
      
        else
        {                 return response([
            'error' => [
                'code' => 'INSUFFICIENT_ROLE',
                'description' => 'You are not authorized to access this resource.'
            ]
        ], 401);  
        }
         }     
    } 
        private function getRequiredRoleForRoute($route)
    {
        $actions = $route->getAction();
        return isset($actions['roles']) ? $actions['roles'] : null;
    }
}.

The above codes check the role applied to route with roles of user .

Now we register middleware in kernel.php file in App\Http directory and Add it in route middleware array.
  protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'roles'         => \App\Http\Middleware\CheckRole::class,
    ];

Step 6- Apply middleware to any route in routes.php you wish.

  Route::get('Guest', [
    'middleware' => ['roles'], // A 'roles' middleware must be specified
    'uses' => 'GreetingController@about',
    'roles' => ['User'] ]);


Click here to download all file of this tutorial - Download

Unknown

About Unknown -

Freelancer,Entrepreneur,Aesthetic bodybuilder.

    Knows :
  • Laravel Framework
  • Ionic Framework + Angular JS
  • Bootstrap
  • CSS
  • Jquery

Subscribe to this Blog via Email :