Lecture Notes Of Day 9: Middleware Basics

 

Lecture Notes Of Day 9 

Middleware Basics

Objective:

By the end of this lesson, students will understand the concept of middleware in Laravel and be able to create and use middleware to filter HTTP requests.

Outcome:

Students will be able to:

  • Understand what middleware is and how it works in the Laravel framework.
  • Create custom middleware using the php artisan make:middleware command.
  • Use middleware to filter or modify HTTP requests before they reach the application logic.

1. Introduction to Middleware

Middleware in Laravel is a mechanism that allows you to filter HTTP requests entering your application. It acts as a bridge between the HTTP request and the application logic, and it allows you to perform various tasks before the request is handled by your application's controllers.

Middleware can perform various tasks such as:

  • Authentication: Checking if a user is logged in before accessing certain parts of the application.
  • Logging: Logging request details, such as IP address, user-agent, etc.
  • CSRF Protection: Protecting your application from cross-site request forgery attacks.
  • Modifying Request Data: Altering or sanitizing the request data before it reaches the controller.

Each HTTP request in Laravel passes through a stack of middleware, and the request is either allowed to proceed to the controller or blocked, depending on the logic in the middleware.


2. How Middleware Works in Laravel

When a request enters your Laravel application, it goes through a sequence of middleware layers. This sequence is determined by the middleware stack defined in app/Http/Kernel.php.

Middleware can be assigned to specific routes or groups of routes. Here's a breakdown of how middleware works:

1.  Request comes to the Application: The incoming HTTP request hits the application.

2.  Middleware Handling: The request passes through all middleware layers defined for that request.

3.  Controller: If the request passes all middleware, it reaches the controller and performs the intended action.

4.  Response: Once the action is performed, the response can pass through middleware again before it’s sent back to the user.


3. Creating Middleware

Laravel makes it easy to create custom middleware using the Artisan command-line tool. You can generate a middleware class using the following command:

php artisan make:middleware CheckAge

This command will generate a new middleware class at app/Http/Middleware/CheckAge.php.


4. Middleware Structure

Once you create the middleware, you will see that it includes two main methods:

  • handle(): This method is where you define the logic to filter requests.
  • terminate(): This method is optional and is used when you need to perform actions after the response is sent back to the browser. (Most beginners don’t need to use this method right away.)

Example of a basic CheckAge middleware:

php

Copy code

namespace App\Http\Middleware;

 

use Closure;

 

class CheckAge

{

    /**

     * Handle an incoming request.

     *

     * @param  \Illuminate\Http\Request  $request

     * @param  \Closure  $next

     * @return mixed

     */

    public function handle($request, Closure $next)

    {

        // Check if the user's age is greater than 18

        if ($request->age < 18) {

            return response('You are not old enough.', 403);

        }

 

        // Continue to the next middleware or the controller

        return $next($request);

    }

}

In this example, the handle() method checks the age from the request, and if the age is less than 18, it sends a 403 Forbidden response. Otherwise, it passes the request to the next middleware or controller.


5. Registering Middleware

After creating your custom middleware, you need to register it within the Laravel application. This is done in the app/Http/Kernel.php file.

  • Global Middleware: Middleware that runs on every HTTP request.
  • Route Middleware: Middleware that can be assigned to specific routes.

To register your middleware as route middleware, open the app/Http/Kernel.php file and add your middleware to the $routeMiddleware array.

php

Copy code

protected $routeMiddleware = [

    // Other middleware...

    'check.age' => \App\Http\Middleware\CheckAge::class,

];


6. Using Middleware in Routes

Once the middleware is registered, you can apply it to specific routes. You can do this by using the middleware method in your route definitions.

Example of using the CheckAge middleware on a route:

php

Copy code

use Illuminate\Support\Facades\Route;

 

Route::get('/profile', function () {

    return 'You have access to this page!';

})->middleware('check.age');

In this example, the CheckAge middleware will be executed before the profile route is accessed. If the user is under 18, they will receive a 403 response; otherwise, the profile page is shown.


7. Middleware Groups

Laravel allows you to group middleware. This is useful when you want to apply multiple middleware to a route without repeating the middleware in each route definition.

For example, you can group middleware for routes that require authentication and role checks.

In app/Http/Kernel.php, you can define middleware groups like so:

php

Copy code

protected $middlewareGroups = [

    'web' => [

        \App\Http\Middleware\EncryptCookies::class,

        \App\Http\Middleware\VerifyCsrfToken::class,

        // other web middleware

    ],

 

    'api' => [

        \App\Http\Middleware\Authenticate::class,

        // other API-specific middleware

    ],

];

Then, you can apply the group of middleware to a route:

php

Copy code

Route::middleware('web')->group(function () {

    Route::get('/dashboard', function () {

        return 'Welcome to the dashboard!';

    });

});


8. Middleware Terminology

  • Handle: The method used to filter the request before it reaches the controller.
  • Terminate: The optional method for actions after the response is sent back to the user.
  • Global Middleware: Middleware that runs on every request.
  • Route Middleware: Middleware applied only to specific routes.
  • Middleware Groups: Grouped middleware to apply multiple middlewares at once.

9. Exercise: Create and Use Custom Middleware

Objective: Create a middleware that checks if a user is authenticated before accessing a route.

1.  Create a middleware named CheckAuth.

2.  In the handle() method, check if the user is authenticated by checking a session variable or any method you prefer (e.g., auth()->check()).

3.  If the user is not authenticated, return a 401 Unauthorized response.

4.  Apply this middleware to a route, such as a user dashboard route.


10. Summary

  • Middleware provides a way to filter HTTP requests entering the application.
  • You can create custom middleware with the php artisan make:middleware command.
  • Middleware can be used for tasks such as authentication, logging, CSRF protection, and more.
  • Middleware is registered in the Kernel.php file and can be assigned to routes as needed.
  • You can group multiple middleware together and apply them to routes.


Comments

Popular posts from this blog

MCQs Of Day CRUD 8 Operations with Eloquent

Lecture Notes Of Day 24: Laravel Policies

MCQs of Day 7 Eloquent ORM Basics