Laravel User Access Control using Middleware Example

By Hardik Savani April 16, 2024 Category : Laravel

We always require to built user access control in our application, when we start. I posted User ACL Roles and Permissions using entrust for laravel 5 application. But as you can see on my post it is very useful and fantastic, But if you have big application or like e-commerce application. Because User ACL is take a time to implement. Yes, if you have small or medium level application and you don't require to make permission with module wise, So at that time it is better if you make simple use access control.

So, In this tutorial i want to share with you how to make very simple user access control using middleware and custom helper in our laravel 5, laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 application. That way you don't take long time to implement and it very simple.

In this example i will create create three roles as pre-define as bellow listed:

1)User:

2)Admin:

3)Superadmin:

In this three role, we will use in whole application like every use have at least one user role and he can access as we want. So we can create three level of user and according to that level user can access that pages an d route. So we will learn how to implement this types of role and permission by following few step, So let's start:


Step 1 : Install Laravel Application

This tutorial is from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog

Step 2 : Add New Column

After getting fresh Laravel application successfully, we need one column "is_permission" in users table. This column will maintain which role of this user. let's see bellow for role:

1)is_permission = 0: User Role

2)is_permission = 1: Admin Role

3)is_permission = 2: Superadmin Role

Now we have to change users migration before run so let's open your users table migration and it should looks like as bellow:

users table migration:

<?php


use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;


class CreateUsersTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('users', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('email')->unique();

$table->string('password');

$table->rememberToken();

$table->tinyInteger('is_permission');

$table->timestamps();

});

}


/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('users');

}

}

After bellow modification you have run migration by following command:

php artisan migrate

Step 3 : Create Authentication

In this step, we require to make authentication module using laravel command. that way laravel automatic create login, register and home page with laravel layout. I also posted for "Create authentication(login and registration)" that way you can understand how it is work. So let's proceed and run bellow command and create auth.

make auth:

php artisna make:auth

After run bellow command you have created login, register and home page.

Step 4 : Create Custom Helper

In this step, we require to create our custom helper method. This method will always check user are able for specific role. I also posted "How to create custom helpers in laravel ?". As i posted we have to create our custom helper by following code, So first create helpers file on Http folder. In this file i created two method checkPermission() and getMyPermission() that will help to check permission in blade view file as well. So let's follow:

app/Http/helpers.php

<?php


function checkPermission($permissions){

$userAccess = getMyPermission(auth()->user()->is_permission);

foreach ($permissions as $key => $value) {

if($value == $userAccess){

return true;

}

}

return false;

}


function getMyPermission($id)

{

switch ($id) {

case 1:

return 'admin';

break;

case 2:

return 'superadmin';

break;

default:

return 'user';

break;

}

}


?>

now we have to put path of helpers file,so basically open composer.json file and put following code in that file:

composer.json

"autoload": {

"classmap": [

...

],

"psr-4": {

"App\\": "app/"

},

"files": [

"app/Http/helpers.php" //Add This Line

]

},

At last we should just run following command:

composer dump-autoload

Ok, now we are ready to use checkPermission() in anywhere in our laravel application.

Step 5 : Create Custom Middleware

In this step we need to create custom middleware with parameters of role. this middleware will check user are ability to access this route. So we require to create custom middleware. I also posted "How to create and use Middleware in Laravel 5?" that way you can learn how to create middleware from scratch. So let's create "CheckPermission" middleware by following command:

php artisan make:middleware CheckPermission

Ok, now you can found CheckPermission.php in app/Http/Middleware directory and open CheckPermission.php file and put bellow code on that file. In this file i check first if user is able to access for current route:

app/Http/Middleware/CheckPermission.php

<?php


namespace App\Http\Middleware;


use Closure;


class CheckPermission

{

/**

* Handle an incoming request.

*

* @param \Illuminate\Http\Request $request

* @param \Closure $next

* @return mixed

*/

public function handle($request, Closure $next, $permission)

{

$permission = explode('|', $permission);


if(checkPermission($permission)){

return $next($request);

}


return response()->view('errors.check-permission');

}

}

Now we need to register and create alias above middleware in Kernel.php file so first open Kernel.php and add bellow line.

app/Http/Kernel.php

<?php


namespace App\Http;


use Illuminate\Foundation\Http\Kernel as HttpKernel;


class Kernel extends HttpKernel

{


......


protected $routeMiddleware = [


......


'check-permission' => \App\Http\Middleware\CheckPermission::class,


];


}

Ok, now we can use "check-permission" middleware in your controller.

Step 6: Create New Route

In this is step we need to create routes for add new items and listing. so open your routes/web.php file and add following route.

routes/web.php

Auth::routes();


Route::get('/home', 'HomeController@index');


Route::group(['middleware'=>'auth'], function () {

Route::get('permissions-all-users',['middleware'=>'check-permission:user|admin|superadmin','uses'=>'HomeController@allUsers']);

Route::get('permissions-admin-superadmin',['middleware'=>'check-permission:admin|superadmin','uses'=>'HomeController@adminSuperadmin']);

Route::get('permissions-superadmin',['middleware'=>'check-permission:superadmin','uses'=>'HomeController@superadmin']);

});

Step 7: Add Controller Method

In this step, we will add new method for testing demo on HomeController. So we have to put bellow code on our HomeController:

app/Http/Controllers/HomeController.php

<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;


class HomeController extends Controller

{

/**

* Create a new controller instance.

*

* @return void

*/

public function __construct()

{

$this->middleware('auth');

}


/**

* Show the application dashboard.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

return view('home');

}


/**

* Show the application dashboard.

*

* @return \Illuminate\Http\Response

*/

public function allUsers()

{

dd('Access All Users');

}


/**

* Show the application dashboard.

*

* @return \Illuminate\Http\Response

*/

public function adminSuperadmin()

{

dd('Access Admin and Superadmin');

}


/**

* Show the application dashboard.

*

* @return \Illuminate\Http\Response

*/

public function superadmin()

{

dd('Access only Superadmin');

}

}

Step 8: Add View Blade Files

In last step, we will add new one blade file and one modify. First we will modify view file. Now you can see home.blade.php file on your resources folder. In this file we added three buttons for check current user access control:

If "is_permission=0" then you can see only "Access All Users" button.

If "is_permission=1" then you can see "Access All Users" button and "Access Admin and Superadmin".

If "is_permission=2" then you can see all button

So let's modify home blade file:

resources/views/home.blade.php

@extends('layouts.app')


@section('content')

<div class="container">

<div class="row">

<div class="col-md-12">

<div class="panel panel-default">

<div class="panel-heading">Manage Permission</div>


<div class="panel-body">


@if(checkPermission(['user','admin','superadmin']))

<a href="{{ url('permissions-all-users') }}"><button>Access All Users</button></a>

@endif


@if(checkPermission(['admin','superadmin']))

<a href="{{ url('permissions-admin-superadmin') }}"><button>Access Admin and Superadmin</button></a>

@endif


@if(checkPermission(['superadmin']))

<a href="{{ url('permissions-superadmin') }}"><button>Access Only Superadmin</button></a>

@endif


</div>

</div>

</div>

</div>

</div>

@endsection

Now we have to create new blade file for middleware permission, If you don't have access for route then you will found bellow file layout. So create new file:

resources/views/errors/check-permission.blade.php

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="/css/app.css" rel="stylesheet">

<title>{{ config('app.name', 'Laravel') }}</title>

</head>

<body>


<div class="container text-center">

<h1>You don't have permission for access this page <br/> Please contact you Superadmin!</h1>

</div>


</body>

</html>

Before, run this example you have create seeder for sample users : "Laravel 5 - Example of Database Seeder with insert sample data".

Now we are ready to run our example so run bellow command for quick run:

php artisan serve

Now you can open bellow url on your browser:

http://localhost:8000/login

I hope it can help you....

Shares