{"id":1374,"date":"2024-09-03T17:22:53","date_gmt":"2024-09-03T17:22:53","guid":{"rendered":"https:\/\/quizonlines.com\/blog-temp\/?p=1374"},"modified":"2024-09-15T18:10:04","modified_gmt":"2024-09-15T18:10:04","slug":"create-custom-middleware-in-laravel-11","status":"publish","type":"post","link":"https:\/\/debugspot.com\/blogs\/create-custom-middleware-in-laravel-11\/","title":{"rendered":"How to Create Custom Middleware in Laravel 11"},"content":{"rendered":"<p>Learn how to create custom middleware in Laravel 11 with this comprehensive step-by-step guide. This tutorial covers the installation of Laravel 11, the creation of middleware, and applying it to routes, providing you with the knowledge to effectively manage middleware in your Laravel applications.<\/p>\n<p>Laravel 11 introduces significant changes to middleware handling compared to previous versions. Previously, middleware was registered in the Kernel.php file, but now, Laravel 11 requires you to define middleware in the app.php file. This update streamlines middleware management and enhances flexibility in handling HTTP requests.<\/p>\n<p>Middleware in Laravel provides a convenient mechanism for inspecting and filtering HTTP requests entering your application. With custom middleware, you can implement various functionalities such as authentication, logging, and more.<\/p>\n<p>In this guide, we\u2019ll explore how to create custom middleware in Laravel 11, customize default middleware, and understand its application in Laravel 11.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/debugspot.com\/blogs\/create-custom-middleware-in-laravel-11\/#Step_1_Install_Laravel_11\" >Step 1: Install Laravel 11<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/debugspot.com\/blogs\/create-custom-middleware-in-laravel-11\/#Step_2_Create_Middleware_in_Laravel_11\" >Step 2: Create Middleware in Laravel 11<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/debugspot.com\/blogs\/create-custom-middleware-in-laravel-11\/#Step_3_Edit_Middleware_appHttpMiddlewareIsAdminphp\" >Step 3: Edit Middleware (app\/Http\/Middleware\/IsAdmin.php)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/debugspot.com\/blogs\/create-custom-middleware-in-laravel-11\/#Step_4_Register_Custom_Middleware_in_Laravel_11\" >Step 4: Register Custom Middleware in Laravel 11<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/debugspot.com\/blogs\/create-custom-middleware-in-laravel-11\/#Step_5_Apply_Middleware_to_Routes\" >Step 5: Apply Middleware to Routes<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/debugspot.com\/blogs\/create-custom-middleware-in-laravel-11\/#Step_6_Run_the_Laravel_11_Application\" >Step 6: Run the Laravel 11 Application<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/debugspot.com\/blogs\/create-custom-middleware-in-laravel-11\/#Summary\" >Summary<\/a><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/debugspot.com\/blogs\/create-custom-middleware-in-laravel-11\/#You_may_also_find_interesting\" >You may also find interesting:<\/a><\/li><\/ul><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_1_Install_Laravel_11\"><\/span>Step 1: Install Laravel 11<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>To start, we need to install Laravel 11. Open your terminal and run the following Composer command:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">composer create-project --prefer-dist laravel\/laravel laravel-11-example<\/code><\/pre>\n<p>This command sets up a fresh Laravel 11 project in a directory named &#8220;laravel-11-example&#8221;. You can now proceed to add your custom middleware.<\/p>\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_2_Create_Middleware_in_Laravel_11\"><\/span>Step 2: Create Middleware in Laravel 11<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Once Laravel is installed, the next step is to create middleware. Use the following Artisan command to generate a new middleware class:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">php artisan make:middleware IsAdmin<\/code><\/pre>\n<p>This command creates a new middleware file called IsAdmin.php under the app\/Http\/Middleware directory. You can now define your custom logic in this file.<\/p>\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_3_Edit_Middleware_appHttpMiddlewareIsAdminphp\"><\/span>Step 3: Edit Middleware (app\/Http\/Middleware\/IsAdmin.php)<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Open the newly created IsAdmin.php file and add the following code to handle requests based on user roles:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\"> namespace App\\Http\\Middleware;\r\nuse Closure; use Illuminate\\Http\\Request; use Symfony\\Component\\HttpFoundation\\Response;\r\n\r\nclass IsAdmin {\r\n     public function handle(Request $request, Closure $next): Response {\r\n         if (\\Auth::user()->role_id != 1) {\r\n             return response()->json('Oops! You do not have permission to access.'); \r\n            } \r\n        return $next($request); \r\n    } \r\n} <\/code><\/pre>\n<p>This middleware checks if the authenticated user has the role of an admin. If not, it returns a JSON response denying access.<\/p>\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_4_Register_Custom_Middleware_in_Laravel_11\"><\/span>Step 4: Register Custom Middleware in Laravel 11<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>To use the custom middleware, you need to register it in the bootstrap\/app.php file. Here\u2019s how you do it:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\"> \r\nuse Illuminate\\Foundation\\Application;\r\n use Illuminate\\Foundation\\Configuration\\Exceptions; \r\n use Illuminate\\Foundation\\Configuration\\Middleware;\r\nreturn Application::configure(basePath: dirname(DIR))\r\n ->withRouting( web: DIR.'\/..\/routes\/web.php', commands: DIR.'\/..\/routes\/console.php', health: '\/up', )\r\n  ->withMiddleware(function (Middleware $middleware) {\r\n           $middleware->alias([ 'isAdmin' => \\App\\Http\\Middleware\\IsAdmin::class, ]);\r\n }) \r\n  ->withExceptions(function (Exceptions $exceptions) { \/\/ })->create(); \r\n<\/code><\/pre>\n<p>By adding this code, you ensure that the isAdmin middleware is registered and available for use in your application.<\/p>\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_5_Apply_Middleware_to_Routes\"><\/span>Step 5: Apply Middleware to Routes<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>With the middleware registered, you can now apply it to specific routes in routes\/web.php. Here\u2019s how:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\"> use Illuminate\\Support\\Facades\\Route;\r\nRoute::middleware(['isAdmin'])->group(function () {\r\n     Route::get('\/dashboard', function () { return 'Dashboard';\r\n });\r\n\r\nRoute::get('\/users', function () {\r\n    return 'Users';\r\n});\r\n}); \r\n<\/code><\/pre>\n<p>This setup restricts access to the \/dashboard and \/users routes to users who pass the isAdmin middleware check.<\/p>\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_6_Run_the_Laravel_11_Application\"><\/span>Step 6: Run the Laravel 11 Application<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Finally, to test the middleware, start the Laravel application using the following command:<\/p>\n<pre class=\"highlight-height line-numbers language-javascript\"><code class=\"language-javascript\">php artisan serve<\/code><\/pre>\n<p>Access your application in a web browser to see the middleware in action. You should see the restricted routes only accessible to users with the correct role.<\/p>\n<p>For more detail you can write <a href=\"https:\/\/laravel.com\/docs\/11.x\/middleware\" target=\"_blank\" rel=\"noopener\">Laravel Documentation<\/a> <\/p>\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Summary\"><\/span>Summary<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Creating custom middleware in Laravel 11 is a straightforward process that provides powerful control over how your application handles HTTP requests. By following these steps, you can manage user permissions and customize request handling to meet your application&#8217;s needs.<\/p>\n<h5><span class=\"ez-toc-section\" id=\"You_may_also_find_interesting\"><\/span>You may also find interesting:<span class=\"ez-toc-section-end\"><\/span><\/h5>\n<p><a href=\"https:\/\/debugspot.com\/blogs\/fcm-notification-google-laravel-11\/\" target=\"_blank\" title=\"Implement push notification in Laravel 11\" rel=\"noopener\">FCM Notification in Laravel 11<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to create custom middleware in Laravel 11 with this comprehensive step-by-step guide. This tutorial covers the installation of Laravel 11, the creation of middleware, and applying it to routes, providing you with the knowledge to effectively manage middleware in your Laravel applications. Laravel 11 introduces significant changes to middleware handling compared to previous versions. Previously, middleware was registered in the Kernel.php file, but now, Laravel 11 requires you to define middleware in the app.php file. This update streamlines middleware management and enhances flexibility in handling HTTP requests. Middleware in Laravel provides a convenient mechanism for inspecting and filtering HTTP requests entering your application. With custom middleware, you can implement various functionalities such as authentication, logging, and more. In this guide, we\u2019ll explore how to create custom middleware in Laravel 11, customize default middleware, and understand its application in Laravel 11. Step 1: Install Laravel 11 To start, we need to install Laravel 11. Open your terminal and run the following Composer command: composer create-project &#8211;prefer-dist laravel\/laravel laravel-11-example This command sets up a fresh Laravel 11 project in a directory named &#8220;laravel-11-example&#8221;. You can now proceed to add your custom middleware. Step 2: Create Middleware in Laravel 11 Once &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"rank_math_lock_modified_date":false,"footnotes":""},"categories":[3],"tags":[32,30,31,33,34],"class_list":["post-1374","post","type-post","status-publish","format-standard","hentry","category-laravel","tag-custom-middleware","tag-laravel-11","tag-laravel-middleware","tag-middleware-configuration","tag-middleware-in-laravel"],"acf":[],"_links":{"self":[{"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/posts\/1374"}],"collection":[{"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/comments?post=1374"}],"version-history":[{"count":9,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/posts\/1374\/revisions"}],"predecessor-version":[{"id":1505,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/posts\/1374\/revisions\/1505"}],"wp:attachment":[{"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/media?parent=1374"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/categories?post=1374"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/debugspot.com\/blogs\/wp-json\/wp\/v2\/tags?post=1374"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}