{"id":11764,"date":"2025-12-17T15:36:54","date_gmt":"2025-12-17T10:06:54","guid":{"rendered":"https:\/\/www.youstable.com\/blog\/?p=11764"},"modified":"2025-12-24T16:13:12","modified_gmt":"2025-12-24T10:43:12","slug":"how-to-use-middleware-in-laravel","status":"publish","type":"post","link":"https:\/\/www.youstable.com\/blog\/how-to-use-middleware-in-laravel","title":{"rendered":"How to Use Middleware in Laravel with Example in 2026"},"content":{"rendered":"\n<p><a href=\"https:\/\/web.archive.org\/web\/20250718073746\/https:\/\/www.youtube.com\/@WebTechKnowledge\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><strong>Middleware in Laravel acts as a bridge<\/strong> between a request and a response. It provides a convenient mechanism for filtering HTTP requests entering your application. Whether verifying a user is authenticated, logging the request, or modifying headers, middleware is crucial in Laravel\u2019s request lifecycle.<\/p>\n\n\n\n<p>In Laravel, middleware is essential because it helps you encapsulate logic that should be applied to a group of routes or every request. Middleware makes your application more organized and secure, from built-in functionalities like CSRF protection to custom logic for role checking.<\/p>\n\n\n\n<p>Laravel\u2019s built-in middleware system is robust and easy to extend. It includes global middleware that applies to all requests, route-specific middleware, and grouped middleware for managing complex stacks.<\/p>\n\n\n\n<p>In this article, you\u2019ll learn how to use middleware in Laravel, including its types, how to create and apply custom middleware, and everyday use cases like authentication and logging\u2014all with best practices for clean, efficient code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"types-of-middleware-in-laravel\">Types of Middleware in Laravel<\/h2>\n\n\n\n<p>Laravel provides different types of middleware to handle HTTP requests efficiently. Each type serves a unique purpose some run globally on every request, while others apply only to specific routes or groups. Understanding these types helps you organize your application and apply logic exactly where needed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"global-middleware\">Global Middleware<\/h3>\n\n\n\n<p>Global middleware is executed for every HTTP request that enters your Laravel application. It is typically used for tasks that must always be performed, such as trimming input strings, handling proxies, or verifying CSRF tokens.<\/p>\n\n\n\n<p>These are registered in the&nbsp;<code>$middleware<\/code>&nbsp;array of the&nbsp;<code>app\/Http\/Kernel.php<\/code>&nbsp;file.<\/p>\n\n\n\n<p><strong>Examples:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>\\Illuminate\\Foundation\\Http\\Middleware\\TrimStrings<\/code><\/li>\n\n\n\n<li><code>\\App\\Http\\Middleware\\VerifyCsrfToken<\/code><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"route-middleware\"><strong>Route Middleware<\/strong><\/h3>\n\n\n\n<p>Route middleware is assigned to specific routes or route groups. It\u2019s used to apply checks or logic only where needed, such as requiring authentication or restricting access to guests.<br>These are registered in the&nbsp;<code>$routeMiddleware<\/code>&nbsp;array of the&nbsp;<code>app\/Http\/Kernel.php<\/code>&nbsp;file.<\/p>\n\n\n\n<p><strong>Examples:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>'auth' =&gt; \\App\\Http\\Middleware\\Authenticate::class<\/code><\/li>\n\n\n\n<li><code>'guest' =&gt; \\App\\Http\\Middleware\\RedirectIfAuthenticated::class<\/code><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"middleware-groups\"><strong>Middleware Groups<\/strong><\/h3>\n\n\n\n<p>Middleware groups allow you to bundle multiple middleware under a single key to simplify route definitions. These are useful for applying a standard set of middleware, like those needed for web or API routes.<br>They are defined in the&nbsp;<code>$middlewareGroups<\/code>&nbsp;array in the&nbsp;<code>app\/Http\/Kernel.php<\/code>&nbsp;file.<\/p>\n\n\n\n<p><strong>Examples:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>'web' =&gt; [\\App\\Http\\Middleware\\EncryptCookies::class, ...]<\/code><\/li>\n\n\n\n<li><code>'api' =&gt; ['throttle:api', \\Illuminate\\Routing\\Middleware\\SubstituteBindings::class]<\/code><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"custom-middleware\"><strong>Custom Middleware<\/strong><\/h3>\n\n\n\n<p>Custom middleware is user-defined and created to handle specific application logic that doesn\u2019t come out of the box with Laravel, such as checking user roles or blocking particular IPs.<br>Created using Artisan and registered in&nbsp;<code>Kernel.php<\/code>, either globally or as route middleware.<\/p>\n\n\n\n<p><strong>Examples:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>php artisan make:middleware CheckIfAdmin<\/code><\/li>\n\n\n\n<li><code>\\App\\Http\\Middleware\\CheckIfAdmin::class<\/code><\/li>\n<\/ul>\n\n\n\n<p><em>Check Out |&nbsp;<a href=\"https:\/\/www.youstable.com\/blog\/raid-explained\/\">RAID Explained: Understanding RAID 0, 1, 5, and 10 for Beginners<\/a><\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"create-and-register-custom-middleware-in-laravel\"><strong>Create and Register Custom Middleware in Laravel<\/strong><\/h2>\n\n\n\n<p>Creating custom middleware in Laravel allows you to define and apply your request-handling logic, such as checking user roles, blocking IPs, or modifying request data. It helps keep your code clean and reusable by isolating specific functionality from controllers or routes.<\/p>\n\n\n\n<p><strong>Steps to Create Custom Middleware in Laravel<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Create the Middleware Class<\/strong><\/li>\n<\/ul>\n\n\n\n<p>Use the Artisan command to generate a new middleware file:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nphp artisan make:middleware CheckIfAdmin\n<\/pre><\/div>\n\n\n<p>This creates a file at&nbsp;<code>app\/Http\/Middleware\/CheckIfAdmin.php<\/code>.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Define the Logic in&nbsp;<code>handle()<\/code>&nbsp;Method<\/strong><\/li>\n<\/ul>\n\n\n\n<p>Open the newly created file and implement your custom logic using the&nbsp;<code>handle()<\/code>&nbsp;technique. Use&nbsp;<code>$next($request)<\/code>&nbsp;to continue the request lifecycle.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public function handle($request, Closure $next)\n{\n    if (!auth()-&gt;check() || !auth()-&gt;user()-&gt;isAdmin()) {\n        return redirect('\/home');\n    }\n\n    return $next($request);\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"register-the-middleware\"><strong>Register the Middleware<\/strong><\/h3>\n\n\n\n<p>To use your middleware, register it in&nbsp;<code>app\/Http\/Kernel.php<\/code>.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>As Route Middleware<\/strong>&nbsp;(recommended):<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>protected $routeMiddleware = &#91;\n    'admin' =&gt; \\App\\Http\\Middleware\\CheckIfAdmin::class,\n];<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>As Global Middleware<\/strong>&nbsp;(less common):<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>protected $middleware = &#91;\n    \\App\\Http\\Middleware\\CheckIfAdmin::class,\n];<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"apply-middleware-to-routes\">Apply Middleware to Routes<\/h3>\n\n\n\n<p>Once registered, apply it to routes or controllers.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Single Route:<\/strong><\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>Route::get('\/admin', function () {\n    \/\/ Admin dashboard\n})-&gt;middleware('admin');<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Controller Constructor:<\/strong><\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>public function __construct()\n{\n    $this-&gt;middleware('admin');\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"testing-your-middleware\">Testing Your Middleware<\/h3>\n\n\n\n<p>Finally, testing your middleware to confirm it behaves correctly is essential. You can do this by:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Logging in with a&nbsp;<strong>non-admin account<\/strong>&nbsp;and trying to access the protected route to verify it redirects as intended.<\/li>\n\n\n\n<li>Logging in with an&nbsp;<strong>admin account<\/strong>&nbsp;to ensure the route is accessible without any issues.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"use-middleware-in-laravel-with-example\">Use Middleware in Laravel with Example<\/h2>\n\n\n\n<p>After creating and registering middleware, the next step is to apply it where needed in your application. Laravel allows you to use middleware on individual routes, route groups, or within controller constructors. This helps control access or behavior based on request conditions.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Apply Middleware to a Single Route<\/strong><\/li>\n<\/ul>\n\n\n\n<p>You can apply middleware directly to a route using the&nbsp;<code>middleware()<\/code>&nbsp;method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Route::get('\/admin', function () {\n    return view('admin.dashboard');\n})-&gt;middleware('admin');<\/code><\/pre>\n\n\n\n<p>The&nbsp;<code>admin<\/code>&nbsp;middleware will run before granting access to the&nbsp;<code>\/admin<\/code>&nbsp;route.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Apply Middleware to Route Groups<\/strong><\/li>\n<\/ul>\n\n\n\n<p>If multiple routes share the same middleware, group them:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Route::middleware(&#91;'admin'])-&gt;group(function () {\n    Route::get('\/admin', 'AdminController@index');\n    Route::get('\/admin\/settings', 'AdminController@settings');\n});<\/code><\/pre>\n\n\n\n<p>All routes in this group will pass through the&nbsp;<code>admin<\/code>&nbsp;middleware.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Apply Middleware in Controller Constructor<\/strong><\/li>\n<\/ul>\n\n\n\n<p>You can also use middleware inside a controller\u2019s constructor:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class AdminController extends Controller\n{\n    public function __construct()\n    {\n        $this-&gt;middleware('admin');\n    }\n\n    public function index()\n    {\n        \/\/ Admin dashboard\n    }\n}<\/code><\/pre>\n\n\n\n<p>This applies to the&nbsp;<code>admin<\/code>&nbsp;middleware for all methods in the controller, keeping your route file clean.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"common-use-cases-for-middleware\"><strong>Common Use Cases for Middleware<\/strong><\/h2>\n\n\n\n<p>Middleware in Laravel helps handle application-wide concerns that affect incoming HTTP requests. Here are some of the most common scenarios where middleware is used:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"csrf-protection\"><strong>CSRF Protection<\/strong><\/h3>\n\n\n\n<p>The&nbsp;<code>VerifyCsrfToken<\/code>&nbsp;Middleware is used to protect applications from cross-site request forgery attacks. It ensures that any form submissions or POST requests include a valid CSRF token. This middleware is part of Laravel\u2019s default&nbsp;<code>web<\/code>&nbsp;middleware group and is automatically applied to most web routes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"logging-and-monitoring\"><strong>Logging and Monitoring<\/strong><\/h3>\n\n\n\n<p>Middleware can log incoming requests, track user activity, or monitor performance. For example, it can record the full URL of each request, headers, and IP addresses. This is useful for maintaining server logs, analyzing traffic, or troubleshooting issues in the application.<\/p>\n\n\n\n<p>You can create a middleware to log every request or certain types of data:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\\Log::info('Request Logged:', &#91;'url' =&gt; $request-&gt;fullUrl()]);<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"caching\"><strong>Caching<\/strong><\/h3>\n\n\n\n<p>Middleware can be used to return cached responses for specific requests, especially API endpoints or pages that don\u2019t change frequently. By doing so, the application avoids reprocessing the same request multiple times, improving performance and reducing server load.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"localization\"><strong>Localization<\/strong><\/h3>\n\n\n\n<p>Middleware can automatically detect and set the application\u2019s language based on the user\u2019s browser settings or location. This allows Laravel to serve content in the appropriate language without requiring the user to select their preference manually.<\/p>\n\n\n\n<p>You can use middleware to detect and set the application\u2019s locale based on the user\u2019s preferences or location.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>app()-&gt;setLocale($request-&gt;getPreferredLanguage(&#91;'en', 'fr', 'es']));<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"conclusion-how-to-use-middleware-in-laravel\"><strong>Conclusion<\/strong> &#8211; How to Use Middleware in Laravel <\/h3>\n\n\n\n<p>Middleware in Laravel is a powerful way to filter and manage HTTP requests before they reach your core application logic. Whether using built-in middleware like authentication or CSRF protection, or creating custom ones for specific needs like role checks or localization, middleware helps you build cleaner, more maintainable, and secure applications. To dive deeper, check out the official&nbsp;<a href=\"https:\/\/laravel.com\/docs\/middleware\" target=\"_blank\" rel=\"noopener\">Laravel middleware documentation<\/a>.<a href=\"https:\/\/web.archive.org\/web\/20250718073746\/https:\/\/twitter.com\/intent\/tweet?url=https:\/\/www.youstable.com\/blog\/how-to-use-middleware-in-laravel\/\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><a href=\"https:\/\/web.archive.org\/web\/20250718073746\/https:\/\/www.facebook.com\/sharer\/sharer.php?u=https:\/\/www.youstable.com\/blog\/how-to-use-middleware-in-laravel\/\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><a href=\"https:\/\/web.archive.org\/web\/20250718073746\/https:\/\/pinterest.com\/pin\/create\/button\/?url=https:\/\/www.youstable.com\/blog\/how-to-use-middleware-in-laravel\/&amp;media=&amp;description=\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><a href=\"https:\/\/web.archive.org\/web\/20250718073746\/https:\/\/plus.google.com\/share?url=https:\/\/www.youstable.com\/blog\/how-to-use-middleware-in-laravel\/\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><a href=\"https:\/\/web.archive.org\/web\/20250718073746\/mailto:\/?Subject=Awesome%20Post&amp;body=https:\/\/www.youstable.com\/blog\/how-to-use-middleware-in-laravel\/\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Middleware in Laravel acts as a bridge between a request and a response. It provides a convenient mechanism for filtering [&hellip;]<\/p>\n","protected":false},"author":13,"featured_media":14618,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[350],"tags":[2099],"class_list":["post-11764","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-knowledgebase","tag-how-to-use-middleware-in-laravel"],"acf":[],"featured_image_src":"https:\/\/www.youstable.com\/blog\/wp-content\/uploads\/2025\/11\/How-to-Use-Middleware-in-Laravel-with-Example.jpg","author_info":{"display_name":"Prahlad Prajapati","author_link":"https:\/\/www.youstable.com\/blog\/author\/prahladblog"},"_links":{"self":[{"href":"https:\/\/www.youstable.com\/blog\/wp-json\/wp\/v2\/posts\/11764","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.youstable.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.youstable.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.youstable.com\/blog\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/www.youstable.com\/blog\/wp-json\/wp\/v2\/comments?post=11764"}],"version-history":[{"count":2,"href":"https:\/\/www.youstable.com\/blog\/wp-json\/wp\/v2\/posts\/11764\/revisions"}],"predecessor-version":[{"id":14619,"href":"https:\/\/www.youstable.com\/blog\/wp-json\/wp\/v2\/posts\/11764\/revisions\/14619"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.youstable.com\/blog\/wp-json\/wp\/v2\/media\/14618"}],"wp:attachment":[{"href":"https:\/\/www.youstable.com\/blog\/wp-json\/wp\/v2\/media?parent=11764"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.youstable.com\/blog\/wp-json\/wp\/v2\/categories?post=11764"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.youstable.com\/blog\/wp-json\/wp\/v2\/tags?post=11764"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}