How to Use Laravel Middleware to Protect Your Application

Aman jain
4 min readJul 12, 2023

--

What is Middleware?

Middleware in Laravel is the programme that executes before a controller responds to a request. It is a method of preventing requests from reaching the controller and processing them instead. Logging, caching, authentication, and permission are just a few applications for this.

Let’s create a middleware example that restricts access to a specific route for non-authenticated users.

Step 1: Create the Middleware.

Execute the following command in your terminal or command prompt:

php artisan make:middleware Authenticate

This command will generate a new file Authenticate.php inside the app/Http/Middleware directory.

Step 2: Define the Middleware Logic

Now , Open the Authenticate.php file and update the handle method with the following code:

<?php

namespace App\Http\Middleware;

use Closure;

class Authenticate
{
public function handle($request, Closure $next)
{
if (!auth()->check()) {
// User is not authenticated, redirect to the login page
return redirect()->route('login')->with('error', 'Please log in to access this page.');
}

// User is authenticated, allow the request to proceed
return $next($request);
}
}

Explanation of Above code

To check whether the user is authenticated in this example, we’re utilising the auth()->check() method. If the user is not authorised, we redirect them to the login route and display an error message. If the user is authenticated, we allow the request to continue by calling $next($request).

Step 3: Register the Middleware.

Open the app/Http/Kernel.php file and add the fully qualified class name of the Authenticate middleware to the $routeMiddleware array:

protected $routeMiddleware = [
// Other middleware...
'auth' => \App\Http\Middleware\Authenticate::class,
];

adding auth=> \App\Http\Middleware\Authenticate::class to the $routeMiddleware array, we are establishing an alias for the Authenticate middleware.

Step 4: Apply the Middleware to Routes.

Now, let’s apply the auth middleware to a route. Open your routes file, usually located at routes/web.php, and add the following route:

Route::get('/dashboard', function () {
// Logic for the dashboard
})->middleware('auth');

In this example, we’ve applied the auth middleware to the /dashboard route. This means that only authenticated users will be able to access the dashboard route.

Unauthenticated users will now be directed to the login page with an error notice if they attempt to access the /dashboard route.Authenticated users will have no trouble accessing the route.

Now you’re all set to create powerful middleware in Laravel! 🚀

Types of Middleware

1.Global Middleware: It applies to all incoming HTTP requests to your application

Example: EncryptCookies encrypts client cookies for security.

// app/Http/Middleware/EncryptCookies.php

namespace App\Http\Middleware;

use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;

class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should be encrypted.
*
* @var array
*/
protected $except = [
//
];
}

Explanation: Global middleware, such as EncryptCookies, is applied to all requests. This example shows how to extend Laravel’s built-in EncryptCookies middleware. The $except attribute lets you specify which cookies should not be encrypted.

2.Route Middleware:Specific routes or route groups are assigned route middleware. It enables you to specify whether middleware should be executed before or after a certain route or set of routes.

// app/Http/Middleware/AdminMiddleware.php

namespace App\Http\Middleware;

use Closure;

class AdminMiddleware
{
public function handle($request, Closure $next)
{
if ($request->user()->isAdmin()) {
return $next($request);
}

abort(403, 'Unauthorized');
}
}

Explanation:Route middleware, such as AdminMiddleware, is assigned to certain routes. In this case, the middleware determines whether the authenticated user is an administrator. If the user is an administrator, the request is forwarded to the next middleware or route handler by calling $next($request). Otherwise, the middleware delivers a 403 Unauthorised error and aborts the request.

3.Controller Middleware: Controller middleware is used directly within the constructor or method of a controller. You may ensure that the middleware is only applied to specified activities within the controller by defining it in the controller.

// app/Http/Controllers/ExampleController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ExampleController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}

public function index()
{
// Controller logic
}
}

Explanation:Controller middleware is used within controller methods, as explained above. The auth middleware is added to the controller’s constructor in this example. This implies that each request to the index method in ExampleController will be routed through the auth middleware, which will determine whether the user is authenticated before allowing the request to proceed.

4.Terminable Middleware:A type of middleware that conducts additional activities after the response has been sent to the browser is known as terminable middleware. This form of middleware can be beneficial for things like logging and resource cleanup.

// app/Http/Middleware/LogRequest.php

namespace App\Http\Middleware;

use Closure;

class LogRequest
{
public function handle($request, Closure $next)
{
return $next($request);
}

public function terminate($request, $response)
{
// Log the request and response
\Log::info('Request: ' . $request->fullUrl());
\Log::info('Response: ' . $response->getContent());
}
}

Explanation: After the response is sent, terminable middleware executes. In this case, the handle method of the LogRequest middleware simply forwards the request to the next middleware or route handler. Laravel then automatically calls the terminate function when the response is sent, allowing you to execute further activities such as logging the request URL and response content.

Congratulations, you absolute coding wizard! 🎉✨ Get ready to subscribe for mind-blowing content that will make your brain do a happy dance! 💃💡 Share the article with your fellow tech enthusiasts and watch their minds explode with joy! Thanks for reading, you awesome human being! 🙌😄 Keep rockin’ that code! 💻🚀

If you want to learn about Mutators and Accessors in Laravel, you can read this article: 📖😊

https://link.medium.com/QyWXdQZonBb

When you have a choice, take your time and make the right choice because if you make the wrong choice, you will have no choice.

--

--