Authentication System and Role Management in Laravel

Authentication versus authorization :- It is the process of verifying identity. Authentication is usually performed by proving the identity bearer has a secret that is known only to the bearer. After an identity is authenticated, authorization is the process of determining who is allowed to do what. So, authorization is accomplished by assigning permission or roles to an identity that accesses system objects.

Permission is the right to access one or more system objects. A role is a group of permissions. That's why, roles can be assigned to any user or user group, and a user or user group can have more than one role. Unlike hierarchical users, a role does not contain another role.

Make Authentication In Laravel :-

Just run PHP artisan make:auth then create all controllers and view that need authentication.

Controllers :-Controllers store in App\Http\Controllers\Auth directory

  • RegisterController:- handles new user registration.
  • LoginController:- handles authentication.
  • ForgotPasswordController :- handles e-mailing links for resetting passwords.
  • ResetPasswordController :- contains the logic to reset passwords.
After adding a new role column to our existing user table then add the role column to the fillable attribute on the User Model in app/User.php

Views :- Views store in resources/views/auth and resources/views/ layouts directory

The file login.blade.php and register.blade.php are storing in resources/views/auth directory. The file app.blade.php is store in resources/views/ layouts directory.

Now we add role select tag input to resources/views/auth/register.blade.php for multiple role management :-


<div class="form-group row solution-sty">
    <label for="role" class="col-md-4 col-form-label text-md-right">Role</label>
       <div class="col-md-6">
        <select name="role" class="form-control" >
            <option value="admin">Admin</option>
            <option value=“vendor">Vendor</option>
        </select>
       </div>
        </div>

Add a new role column to our existing user table :-

After adding a role in view then add a new role column to our existing user table.

Add the role column to the fillable attribute on the User Model :-

After add new rloe column to our existing user table then add the role column to fillable attribute on the User Model in app/User.php


—app/User.php :-
      protected $fillable = [
          'name', 'email', 'password','role',
        ];

Now customize RegisterController.php which is in app/Http/Controllers/Auth directory :-

—include our role input when creating a new user :-


 protected function create(array $data)
                {
               return User::create([
                  'name' => $data['name'],
                  'email' => $data['email'],
                 'password' => bcrypt($data['password']),
                 'role' => $data['role'],
               ]);
            }

Now, We will create middlewares for each of our roles :-

Now, we create middlewares using the Laravel command the commands are below-


php artisan make:middleware Admin    
php artisan make:middleware Vendor

Add the following code to respective middlewares which are located in app/Http/Middleware folder :-

After running the command create two middlewares i.s, Admin.php and Vendor.php in app/Http/Middleware folder now we write code in middlewares

—Admin.php :


use Auth;
function handle($request, Closure $next)
{
    if (Auth::check() && Auth::user()->role == 'admin') {
        return $next($request);
    }
    else {
       return redirect('/');
    }
}

—Vendor.php :


use Auth;
function handle($request, Closure $next)
{
    if (Auth::check() && Auth::user()->role == ‘vendor') {
        return $next($request);
    }
    else {
        return redirect('/');
    }
}

Now let’s register our middleware with Laravel :-

Add the middleware classes to $routeMiddlewareproperty located in app/Http/Kernel.php

//Important section

—Kernel.php :-


 protected $routeMiddleware = [
      'admin' => 'App\Http\Middleware\Admin',
      ‘vendor' => 'App\Http\Middleware\Vendor',
    ];

Now you can apply these middlewares to routes :-

—routes /web.php:


Route::get('/admin', function(){
    echo "Hello Admin";
})->middleware('admin');
Route::get('/vendor', function(){
    echo "Hello Vendor";
})->middleware(‘vendor');

Conclusion:

You can apply the code in laravel development. Please share your reviews in the comment section.

Comments

We Serve clients globally in diverse industries