How to create Laravel middleware that only allows specific users.
Tags: php, laravel, webdev, tutorial
Published: 2023-04-30 13:09:35

Today in this post, you will learn how to create middleware that allows specific users (emails) only in Laravel 8 applications.

Laravel middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to your application’s login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

## **Step1 :Create Helper function that return arrays of the specific users email**

Let's create a function in our helper file that return arrays of specific user's email address. Go to in **app\helpers.php** and create the function

```
function usersThatCanAccessClientLogPage()
    {
        $userEmails = [
            "samadmin@example.com",
            "johndoe@example.com"
        ];
       return $userEmails;
  }
```
We will later call this function when implementing the logic in our middleware.

## **Step 2 :Create Middleware:**

Lets assume there is a page for **Client logs** and only certain email can access that page

Open the terminal and execute the following command to create custom middleware in Laravel 8. So let’s open our command prompt and execute below command:

`php artisan make:middleware CheckClientDownloadPage`

This command will create a new **CheckClientDownloadPage** class within your **app/Http/Middleware** directory

After successfully creating your middleware, go to **app/http/kernel.php** and register your custom middleware here :

```
//Register your CheckClientDownloadPage middleware and import the class
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'client.log' => CheckClientDownloadPage::class,
];
```

## **Step 3: Implement Logic In Middleware:**

After successfully registering your middleware in **app/http/kernel.php**, go to **app/Http/Middleware/CheckClientDownloadPage.php** and implement your logic here :

**app/Http/Middleware/CheckClientDownloadPage.php**

```
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class CheckClientDownloadPage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $loginUser = Auth::user(); // Get the currently authenticated user...
        if (Auth::check()) {
          // The user is logged in...
            if (in_array($loginUser->email, usersThatCanAccessClientLogPage())) {
                return $next($request);
            }
            return redirect('/user/admin/dashboard');
        }
        return redirect('/login');
    }
}
```

## **Step 4:Add Route**

Simply create a Laravel route and use custom middleware with routes to filter every HTTP request:

**routes/web.php**

```
//Route group for route that uses the middleware
Route::middleware(['client.log'])->group(function () {
//add your route here
});
```
Thanks