Laravel 5 how to separate user access with middleware

Published Date: 05-May-2018 | Tags: Laravel 5.5  Middleware  

This tutorial I want to show you how to manage user authorization base on its own role by using middleware in laravel 5. For example, if you want to separate access between Admin and User role, so each of them can only access their own tasks. User cannot access Admin, and Admin cannot access User.

Note: Suppose that your default laravel authentication is working.

 

Step 1: Add role field to users table

Make sure you add column "role" in users table. And its value should store Admin or User.

user-role

 

Step 2: Change redirect after login

Please go to /app/Http/Controllers/Auth/LoginController.php. and change $redirectTo value to "/"

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';


    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

 

Step 3: Add Route

For route in here, after login success, I will check user role and then redirect to their own page.

Auth::routes();
Route::group(['middleware' => 'auth'], function () {
    Route::get('/', function () {
        if (Auth::user()->role == 'Admin')
            return redirect('admin');
        elseif (Auth::user()->role == 'User')
            return redirect('user');
        else
            return redirect('error');
    });
    Route::get('error', function () {
        return "Sorry, you are unauthorized to access this page.";
    });
    Route::group(['prefix' => 'admin', 'middleware' => 'admin'], function () {
        Route::view('/', 'role.admin');
//      Please put all what you want to do with Admin role in here
    });
    Route::group(['prefix' => 'user', 'middleware' => 'user'], function () {
        Route::view('/', 'role.user');
//      Please put all what you want to do with User role in here
    });
});

 

Step 4: Create View

Create layout view file default.blade.php in /resources/views/layout. (create folder layout if it does not exist) 

Note: You can create your own layout. I just place the layout code here in case someone don't know or not clear.

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
@yield('head')
<!-- Styles -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    @yield('css')
</head>
<body style="padding-top: 100px;padding-bottom: 50px;background: whitesmoke">
<nav class="navbar fixed-top navbar-expand-sm navbar-dark bg-info">
    <a class="navbar-brand" target="_blank" href="http://www.codovel.com">CODOVEL.COM</a>
    @yield('nav')
</nav>
@yield('content')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
@yield('js')
</body>
</html>

 

Create view admin.blade.php in /resources/views/role. (create folder role if it does not exist)

@extends('layout.default')
@section('nav')
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
            aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link" target="_blank"
                   href="{{env('website_url')}}/easy-crud-with-laravel-55-step-by-step-tutorial.html">View Post</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" target="_blank"
                   href="javascript:document.getElementById('logout-form').submit();">Logout</a>
            </li>
        </ul>
        <form id="logout-form" action="{{ route('logout') }}" method="POST"
              style="display: none;">
            {{ csrf_field() }}
        </form>
    </div>
@endsection
@section('content')
    <div class="container" style="background: white">
        <br/>
        <h1>Admin</h1>
        <hr/>
        <br/>
    </div>
@endsection

 

Create view user.blade.php in /resources/views/role. (create folder role if it does not exist)

@extends('layout.default')
@section('nav')
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
            aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link" target="_blank"
                   href="{{env('website_url')}}/easy-crud-with-laravel-55-step-by-step-tutorial.html">View Post</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" target="_blank"
                   href="javascript:document.getElementById('logout-form').submit();">Logout</a>
            </li>
        </ul>
        <form id="logout-form" action="{{ route('logout') }}" method="POST"
              style="display: none;">
            {{ csrf_field() }}
        </form>
    </div>
@endsection
@section('content')
    <div class="container" style="background: white">
        <br/>
        <h1>User</h1>
        <hr/>
        <br/>
    </div>
@endsection

 

Step 5: How to test?

Just run your laravel project and login as both Admin and User to see its redirected view.

login-demo

Hope you can do it.


Demo


© 2018 All Rights Reserved.