In this post, you’ll learn how to create middleware with parameters in Laravel 12, step-by-step with code examples.
Middleware in Laravel act as a bridge between requests and responses. .we can say it acts as a filter for HTTP requests coming to your application — allowing you to inspect, modify, or reject requests based on custom logic. Middleware is especially useful for handling tasks that apply across many routes, such as authentication, user role verification, logging, CORS handling, and more.
What makes Laravel’s middleware system even more flexible is its ability to accept parameters. This means you can create dynamic behavior — for example, restricting access to certain routes depending on a user’s role or permissions.
Whether you’re building simple apps or complex enterprise-level solutions, middleware ensures that your application’s HTTP request cycle remains secure, consistent, and modular.
What is Middleware in Laravel?
Middleware in Laravel provides a convenient mechanism for filtering HTTP requests. Think of it as a checkpoint that each request must pass through — allowing you to inspect, modify, or reject requests based on custom logic.
Common use cases:
- Authentication and authorization
- Logging user activity
- CORS and CSRF protection
- Role or permission-based access control
Why Use Middleware with Parameters?
Middleware becomes much more powerful when you pass parameters to it. For example:
- Only allow users with the role “admin” to access a certain route
- Restrict actions based on user subscription status like “Premium”,”Enterprise”,”Free”
- Handle locale or timezone logic dynamically
In Laravel previous versions before laravel 11, middleware was registered in the Kernel.php file using the $middleware and $routeMiddleware arrays.
Starting from Laravel 11, middleware registration has moved to the bootstrap/app.php file. You now use the withMiddleware() method, which provides a cleaner way to register and organize middleware using methods like alias() and appendToGroup().
Step for Create Custom Middleware in Laravel 12
Step 1: Install Laravel 12
Step 2: Create Middleware
Step 3: Register Middleware
Step 4: Apply Middleware
Step 5: Run Laravel App
Prerequisites
- PHP version 8.2 or higher
- Composer (Dependency Manager for PHP)
- MySQL
Step 1: Install Laravel 12
To get started with Laravel 12, you’ll first need to create a fresh Laravel project using Composer, which is the official dependency manager for PHP.
Open your command prompt and run the following command:
composer create-project laravel/laravel laravel-demo-app
This command will download and set up a new Laravel 12 application inside a folder named laravel-demo-app.
Once the installation is complete, go to your newly created project directory:
cd laravel-demo-app
Now you’re ready to begin building and customizing your Laravel application!
Step 2: Create Middleware
To create a new middleware, run the below Artisan command:
php artisan make:middleware CheckAccountType
Executing the above command it will generate a new middleware CheckAccountType class inside the app/Http/Middleware directory. In this middleware, we’ll implement logic to verify the user’s account type — such as free, premium, or enterprise. Based on the account type, the user will be redirected to the appropriate destination. If the account type doesn’t match any expected value, the user will be redirected back to the welcome page.
App\Http\Middleware\CheckAccountType.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class CheckAccountType
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next, ...$account_types): Response
{
if(in_array($request->user()->account_type,$account_types)){
return $next($request);
}
return response()->json("Access Denied: You do not have the necessary permissions to view this page.");
}
}
Step 3: Register Middleware
Open the bootstrap\app.php file. In this step, we will register our custom CheckAccountType middleware using the alias method. Middleware aliases provide a convenient way to reference middleware classes using short, descriptive names, making your code cleaner and more readable.
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
\App\Http\Middleware\HandleInertiaRequests::class,
\Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
]);
$middleware->alias([
'accountType' => \App\Http\Middleware\CheckAccountType::class,
]);
//
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
In app.php, the $middleware object passed to the withMiddleware closure is an instance of Illuminate\Foundation\Configuration\Middleware. It handles the middleware assigned to your application’s routes.
Step 4: Apply Middleware
In this step, we will apply our accountType middleware to specific routes. For demonstration purposes, we’ll define three separate routes — one for premium users, one for free users, and one for enterprise users. After login, the user will be redirected to the appropriate route based on their account type.some routes may be shared by multiple user types. This is a great use case for passing multiple parameters to the middleware. For example, you can allow both premium and enterprise users to access the same route by specifying multiple allowed account types in the middleware declaration.
<?php
use Illuminate\Support\Facades\Route;
Route::middleware('accountType:premium')->group(function () {
Route::get('/premium-content', function () {
return 'Welcome to Premium Content!';
});
});
//enterprise
Route::middleware('accountType:enterprise')->group(function () {
Route::get('/enterprise-dashboard', function () {
return 'Enterprise Dashboard Accessed!';
});
});
Route::middleware('accountType:free')->group(function () {
Route::get('/free-dashboard', function () {
return 'Free Dashboard Accessed!';
});
});
Route::get('/dashboard', function () {
return 'Dashboard Accessed!';
})->middleware('accountType:enterprise,premium,free')->name('dashboard');
Step 5: Run Laravel App
Run the given command given below:
php artisan serve
Now go to your web browser, log in to the application, and the user will be redirected according to their account type.