How to Create Custom Middleware in Laravel 11

How to Create Custom Middleware in Laravel 11

Laravel 11 features invokable controllers, which provide a more concentrated way to managing individual actions within your application. This guide explains how to build and use these controllers, stressing their benefits and providing a practical example.

Advantages of Invokable Controllers:

  1. Enhanced Readability: With a single __invoke method, the controller's purpose is clearly defined, facilitating code maintainability and comprehension.
  2. Reduced Complexity: By requiring less code, maintenance becomes easier, and the development process becomes more streamlined.
  3. Concise Routing: Directly referencing the controller class in Laravel 11 routes without specifying a method simplifies route definitions.

Creating an Invokable Controller in Laravel 11:

  1. Utilize the Artisan Command:

    • Open your terminal and navigate to the root directory of your Laravel 11 project.
    • Execute the following command, replacing ExampleControllerName with your desired name: bash php artisan make:controller ExampleControllerName --invokable This command generates a new controller class with the __invoke method, ready for customization.
  2. Structure the __invoke Method:

    • Open the generated controller file (typically located in app/Http/Controllers).
    • You'll find the __invoke method already defined, where your controller's logic resides.
    • Access the request object using the Request type hint: php public function __invoke(Request $request) { // Your controller logic here } Implement the desired functionality within this method, utilizing Laravel features such as repositories, models, and validation as required.
  3. Define Routes:

    • In your routes file (usually routes/web.php), create a route corresponding to the desired URL: php Route::get('/your-route', ExampleControllerName::class); Replace /your-route with the preferred URI and ExampleControllerName with the actual controller class name.

Example: Handling a Simple Form Submission with an Invokable Controller ```php // app/Http/Controllers/FormController.php

class FormController { public function __invoke(Request $request) { $request->validate([ 'name' => 'required|string', 'email' => 'required|email', ]);

    // Process the form data (e.g., save to database)

    return redirect('/success');


// routes/web.php

Route::post('/submit-form', FormController::class); ```

By following these methods, you can design efficient and maintainable invokable controllers in Laravel 11, resulting in cleaner code and a more pleasant development experience.

  • Date: