Laravel - Middleware (2024)

Previous
Next

Middleware acts as a bridge between a request and a response. It is a type of filtering mechanism. This chapter explains you the middleware mechanism in Laravel.

Laravel includes a middleware that verifies whether the user of the application is authenticated or not. If the user is authenticated, it redirects to the home page otherwise, if not, it redirects to the login page.

Middleware can be created by executing the following command −

php artisan make:middleware <middleware-name>

Replace the <middleware-name> with the name of your middleware. The middleware that you create can be seen at app/Http/Middleware directory.

Example

Observe the following example to understand the middleware mechanism −

Step 1 − Let us now create AgeMiddleware. To create that, we need to execute the following command −

php artisan make:middleware AgeMiddleware

Step 2 − After successful execution of the command, you will receive the following output −

Laravel - Middleware (1)

Step 3AgeMiddleware will be created at app/Http/Middleware. The newly created file will have the following code already created for you.

<?phpnamespace App\Http\Middleware;use Closure;class AgeMiddleware { public function handle($request, Closure $next) { return $next($request); }}

Registering Middleware

We need to register each and every middleware before using it. There are two types of Middleware in Laravel.

  • Global Middleware
  • Route Middleware

The Global Middleware will run on every HTTP request of the application, whereas the Route Middleware will be assigned to a specific route. The middleware can be registered at app/Http/Kernel.php. This file contains two properties $middleware and $routeMiddleware. $middleware property is used to register Global Middleware and $routeMiddleware property is used to register route specific middleware.

To register the global middleware, list the class at the end of $middleware property.

protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class,];

To register the route specific middleware, add the key and value to $routeMiddleware property.

protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,];

Example

We have created AgeMiddleware in the previous example. We can now register it in route specific middleware property. The code for that registration is shown below.

The following is the code for app/Http/Kernel.php

<?phpnamespace App\Http;use Illuminate\Foundation\Http\Kernel as HttpKernel;class Kernel extends HttpKernel { protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ]; protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'Age' => \App\Http\Middleware\AgeMiddleware::class, ];}

Middleware Parameters

We can also pass parameters with the Middleware. For example, if your application has different roles like user, admin, super admin etc. and you want to authenticate the action based on role, this can be achieved by passing parameters with middleware. The middleware that we create contains the following function and we can pass our custom argument after the $next argument.

public function handle($request, Closure $next) { return $next($request);}

Example

Step 1 − Create RoleMiddleware by executing the following command −

php artisan make:middleware RoleMiddleware

Step 2 − After successful execution, you will receive the following output −

Laravel - Middleware (2)

Step 3 − Add the following code in the handle method of the newly created RoleMiddlewareat app/Http/Middleware/RoleMiddleware.php.

<?phpnamespace App\Http\Middleware;use Closure;class RoleMiddleware { public function handle($request, Closure $next, $role) { echo "Role: ".$role; return $next($request); }}

Step 4 − Register the RoleMiddleware in app\Http\Kernel.php file. Add the line highlighted in gray color in that file to register RoleMiddleware.

Laravel - Middleware (3)

Step 5 − Execute the following command to create TestController

php artisan make:controller TestController --plain

Step 6 − After successful execution of the above step, you will receive the following output −

Laravel - Middleware (4)

Step 7 − Copy the following lines of code to app/Http/TestController.php file.

app/Http/TestController.php

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Http\Requests;use App\Http\Controllers\Controller;class TestController extends Controller { public function index() { echo "<br>Test Controller."; }}

Step 8 − Add the following line of code in app/Http/routes.php file.

app/Http/routes.php

Route::get('role',[ 'middleware' => 'Role:editor', 'uses' => 'TestController@index',]);

Step 9 − Visit the following URL to test the Middleware with parameters

http://localhost:8000/role

Step 10 − The output will appear as shown in the following image.

Laravel - Middleware (5)

Terminable Middleware

Terminable middleware performs some task after the response has been sent to the browser. This can be accomplished by creating a middleware with terminate method in the middleware. Terminable middleware should be registered with global middleware. The terminate method will receive two arguments $request and $response. Terminate method can be created as shown in the following code.

Example

Step 1 − Create TerminateMiddleware by executing the below command.

php artisan make:middleware TerminateMiddleware

Step 2 − The above step will produce the following output −

Laravel - Middleware (6)

Step 3 − Copy the following code in the newly created TerminateMiddleware at app/Http/Middleware/TerminateMiddleware.php.

<?phpnamespace App\Http\Middleware;use Closure;class TerminateMiddleware { public function handle($request, Closure $next) { echo "Executing statements of handle method of TerminateMiddleware."; return $next($request); } public function terminate($request, $response) { echo "<br>Executing statements of terminate method of TerminateMiddleware."; }}

Step 4 − Register the TerminateMiddleware in app\Http\Kernel.php file. Add the line highlighted in gray color in that file to register TerminateMiddleware.

Laravel - Middleware (7)

Step 5 − Execute the following command to create ABCController.

php artisan make:controller ABCController --plain

Step 6 − After the successful execution of the URL, you will receive the following output −

Laravel - Middleware (8)

Step 7 − Copy the following code to app/Http/ABCController.php file.

app/Http/ABCController.php

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Http\Requests;use App\Http\Controllers\Controller;class ABCController extends Controller { public function index() { echo "<br>ABC Controller."; }}

Step 8 − Add the following line of code in app/Http/routes.php file.

app/Http/routes.php

Route::get('terminate',[ 'middleware' => 'terminate', 'uses' => 'ABCController@index',]);

Step 9 − Visit the following URL to test the Terminable Middleware.

http://localhost:8000/terminate

Step 10 − The output will appear as shown in the following image.

Laravel - Middleware (9)

Print Page

Previous Next

Advertisem*nts

Laravel - Middleware (2024)
Top Articles
USPS Overnight Shipping: Prices, Features, & More
Are Cashews Good for You? Nutrition, Benefits, and Downsides
This website is unavailable in your location. – WSB-TV Channel 2 - Atlanta
Jail Inquiry | Polk County Sheriff's Office
Jordanbush Only Fans
Danatar Gym
Retro Ride Teardrop
Merlot Aero Crew Portal
Best Restaurants In Seaside Heights Nj
Encore Atlanta Cheer Competition
Cranberry sauce, canned, sweetened, 1 slice (1/2" thick, approx 8 slices per can) - Health Encyclopedia
Sams Gas Price Fairview Heights Il
Synq3 Reviews
Athens Bucket List: 20 Best Things to Do in Athens, Greece
Hoe kom ik bij mijn medische gegevens van de huisarts? - HKN Huisartsen
Kris Carolla Obituary
Busby, FM - Demu 1-3 - The Demu Trilogy - PDF Free Download
Soccer Zone Discount Code
Craigslist Toy Hauler For Sale By Owner
Closest Bj Near Me
Academy Sports Meridian Ms
Knock At The Cabin Showtimes Near Alamo Drafthouse Raleigh
Wics News Springfield Il
How to Make Ghee - How We Flourish
Bento - A link in bio, but rich and beautiful.
Lexus Credit Card Login
Wsbtv Fish And Game Report
The Banshees Of Inisherin Showtimes Near Broadway Metro
Dr. Nicole Arcy Dvm Married To Husband
Is Poke Healthy? Benefits, Risks, and Tips
Where to eat: the 50 best restaurants in Freiburg im Breisgau
His Only Son Showtimes Near Marquee Cinemas - Wakefield 12
Microsoftlicentiespecialist.nl - Microcenter - ICT voor het MKB
Blackstone Launchpad Ucf
Save on Games, Flamingo, Toys Games & Novelties
Tendermeetup Login
Royals op zondag - "Een advertentie voor Center Parcs" of wat moeten we denken van de laatste video van prinses Kate?
Omnistorm Necro Diablo 4
Atlanta Musicians Craigslist
Craigslist Pa Altoona
11526 Lake Ave Cleveland Oh 44102
511Pa
Ucsc Sip 2023 College Confidential
Vintage Stock Edmond Ok
✨ Flysheet for Alpha Wall Tent, Guy Ropes, D-Ring, Metal Runner & Stakes Included for Hunting, Family Camping & Outdoor Activities (12'x14', PE) — 🛍️ The Retail Market
Yale College Confidential 2027
Neil Young - Sugar Mountain (2008) - MusicMeter.nl
Euro area international trade in goods surplus €21.2 bn
Pelican Denville Nj
Image Mate Orange County
How Did Natalie Earnheart Lose Weight
Latest Posts
Article information

Author: Nicola Considine CPA

Last Updated:

Views: 6383

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Nicola Considine CPA

Birthday: 1993-02-26

Address: 3809 Clinton Inlet, East Aleisha, UT 46318-2392

Phone: +2681424145499

Job: Government Technician

Hobby: Calligraphy, Lego building, Worldbuilding, Shooting, Bird watching, Shopping, Cooking

Introduction: My name is Nicola Considine CPA, I am a determined, witty, powerful, brainy, open, smiling, proud person who loves writing and wants to share my knowledge and understanding with you.