Middleware Mayhem! ๐Ÿ•น๏ธ๐Ÿฆธโ€โ™‚๏ธ

Funny Laravel docs · Warning: May cause actual learning AND laughter!

Browse funny laravel docs
On this page

Welcome, code warriors! Buckle up for a wild ride into the world of Laravelโ€™s Middleware Madness! We promise laughs, thrills, and a whole lotta learning. Letโ€™s dive in!

Defining Middleware ๐Ÿ“๐Ÿ’ป

Itโ€™s time to create your very own superheroes (or villainsโ€ฆ nobody judges)! Learn how to define middleware - the unsung heroes of web applications, guarding the gates against digital chaos.

Registering Middleware ๐Ÿ“๐Ÿ”

Now that youโ€™ve made your middlies (thatโ€™s short for middleware), itโ€™s time to get them registered! Here, weโ€™ll share the secrets of getting your guardians of the web recognized and approved.

Global Middleware ๐ŸŒ๐Ÿฆธโ€โ™‚๏ธ

Want your superheroes to protect all incoming requests? Thatโ€™s where global middleware comes in handy! These heroes are always on duty, watching over every corner of your application.

Assigning Middleware to Routes ๐ŸŒโœ‹

Assigning middleware to routes is like giving a mission briefing to a specific superhero team - theyโ€™ll only protect certain areas of your application (routes).

Middleware Groups ๐Ÿฏ๐Ÿ’ช

Grouping middleware makes managing your superheroes easier. Organize them by their powers, skills, or any other category that suits you best!

Middleware Aliases ๐Ÿ“œ๐Ÿ”ข

Sometimes, itโ€™s easier to call our heroes by their aliases instead of their long, fancy names. Middleware aliases let you do just that - making your code more readable and manageable.

Sorting Middleware ๐Ÿ“œ๐Ÿ‹๏ธโ€โ™‚๏ธ

Sorting middleware is like arranging your superhero team in the most effective order to combat digital threats. This way, they can work together seamlessly and efficiently!

Middleware Parameters ๐Ÿ“๐ŸŽฏ

Just like how superheroes have their unique abilities, middleware also comes with parameters that make them customizable to your applicationโ€™s needs.

Terminable Middleware โณ๐Ÿ”ช

Sometimes, even superheroes must fall! Terminable middleware lets you decide when itโ€™s time for a superhero to hang up their cape (or code). This way, you can control exactly when and how your middlies come and go.

We hope this brief tour of Laravelโ€™s Middleware Mayhem has been both entertaining and enlightening! Keep exploring, code warriors โ€“ your web application needs you! ๐Ÿ’ช๐Ÿš€

Ahoy there, intrepid adventurer! Letโ€™s embark on a jolly journey through the enchanting world of Laravel Middleware - your magical sidekicks guarding the gates to your application kingdom. These spritely helpers are like the bouncers at King Arthurโ€™s Round Table, checking each incoming requestโ€™s credentials before letting it pass!

For instance, thereโ€™s a dashing middleware knight that ensures your noble subjects (users) have proven their identity by authenticating themselves. If theyโ€™re just a couple of peasant-ish folks showing up unannounced, heโ€™ll politely redirect them to the login chamber โ€“ aka your applicationโ€™s login screen. But if our valiant knight recognizes the user as a noble king or queen, heโ€™ll let them pass and continue their quest deeper into the application realm.

But donโ€™t let this brave middleware knight hog all the glory! You can craft other fantastical middleware to perform all sorts of magical tasks โ€“ like a log-o-matic mage that keeps tabs on every incoming request, casting spells on the logs to ensure no sneaky orcs infiltrate your kingdom.

In Laravelโ€™s mystical realm, youโ€™ll find quite an assortment of enchanted middleware โ€“ not just the ones for authentication and CSRF protection but many more! All custom-made potions (middleware) should be stored in your applicationโ€™s app/Http/Middleware alchemistโ€™s lab.

So, gather round, ye aspiring sorcerers and sorceresses, as we embark on this thrilling Laravel quest together โ€“ brewing, casting, and perfecting the most magnificent middleware spells to protect and enhance your application kingdom!

Alrighty, letโ€™s craft a new middleware in Laravel Land! Hereโ€™s how:

php artisan make:middleware EnsureTokenIsValid

This command will sprinkle magic fairy dust and create a brand-new EnsureTokenIsValid class in your app/Http/Middleware directory. This little guy will only let access to the route if the supplied token input matches our top-secret code word, โ€œmy-secret-tokenโ€. If the token is fishy, weโ€™ll politely escort the users back to our cozy /home location:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureTokenIsValid
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->input('token') !== 'my-secret-token') {
            // Time to show them the door, my dear
            return redirect('/home');
        }

        // All clear! Proceed with the request.
        return $next($request);
    }
}

Now, if the given token doesnโ€™t jive with our secret code word, this middleware will send an HTTP redirect to the client; otherwise, it lets the request continue on its merry way into the application. To allow the request to proceed deeper into the application (like a friendly doorman waving someone through), call the $next callback with the $request.

Think of middleware as a security checkpoint for incoming requests โ€“ they must pass through multiple layers before they reach your application. Each layer can inspect the request and even deny it entry altogether!

Note

All middleware are resolved via the service container, so you may type-hint any dependencies you need within a middlewareโ€™s constructor.

Alrighty then! Buckle up, folks, because weโ€™re about to dive into the thrilling world of Laravel Middleware and Responses - where every request is an adventure, and every response is a victory dance!

First off, whatโ€™s a middleware? Well, itโ€™s like a superhero sidekick that steps in before or after your request gets all action-packed inside the application. Kinda like Batmanโ€™s Robin, but with less capes and more PHP.

Hereโ€™s an example of a middleware that performs some task before the request is dealt with by Batcave Control:

<?php

namespace App\Http\Middleware;

Use your super powers here!

class BeforeMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        // Perform action - Like Batman doing a fancy flip before saving the day

        return $next($request);
    }
}

Now, letโ€™s check out this middleware that performs its task after the request has been handled:

<?php

namespace App\Http\Middleware;

Use your super powers here!

class AfterMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        // Perform action - Like Batman striking a pose after saving the day

        return $response;
    }
}

Now, youโ€™re probably wondering how to register these middleware sidekicks. Donโ€™t worry, we got you covered! Check out the Registering Middleware section in our documentation for more deets. Remember, a hero is only as good as their team, so donโ€™t forget to bring your A-team of middleware along for the ride!

Ahoy there, Laravel swashbucklers! ๐Ÿดโ€โ˜ ๏ธ Letโ€™s dive into the exciting world of middleware, shall we? This piratey part of our ship (or rather, application) is where you can control the flow of traffic, akin to a lighthouse guiding sailors through treacherous waters.

Global Middleware

Global middleware is like the Captainโ€™s Orders that apply across all routes in your ship (app). To register a global middleware, youโ€™ll need to navigate to app/Http/Kernel.php, hoist the anchor, and find the $middlewareGroups array. Add your shiny new middleware to either the web or api group, depending on where you want it to patrol.

protected $middlewareGroups = [
    'web' => [
        // ...
        \App\Http\Middleware\YourNewMiddleware::class,
    ],

    'api' => [
        // ...
        \App\Http\Middleware\YourNewMiddleware::class,
    ],
];

Registering Custom Middleware

If your global middleware ainโ€™t quite enough and you need a more targeted approach, itโ€™s time to create a custom middleware. Sail over to app/Http/Middleware, carve out a new class, and start coding!

namespace App\Http\Middleware;

use Closure;

class YourCustomMiddleware
{
    public function handle($request, Closure $next)
    {
        // Insert your magical pirate powers here!

        return $next($request);
    }
}

Once youโ€™ve finished crafting your middleware masterpiece, donโ€™t forget to register it in the $routeMiddleware array within the same Kernel.php file, so other parts of the ship can benefit from its awesomeness.

protected $routeMiddleware = [
    // ...
    'your-custom-middleware' => \App\Http\Middleware\YourCustomMiddleware::class,
];

And there you have it, matey! Now you can manage traffic like a seasoned sea captain, ensuring smooth sailing and keeping the treacherous waters at bay. Happy middleware-ing! ๐ŸŒด๐Ÿฌ

Global Middleware Jamboree! ๐ŸŽ‰๐Ÿฅณ

Fancy a middleware thatโ€™s always on the dancefloor, grooving to every HTTP request your application receives? Well, buckle up because weโ€™re about to get this party started in your applicationโ€™s bootstrap/app.php file! ๐Ÿ’ƒ๐Ÿ•บ

Use App\Http\Middleware\EnsureTokenIsValid as YourBouncer;

->withMiddleware(function (Middleware $middleware) {
    $middleware->getMitsubishiLancer()->push_to_the_back(YourBouncer::class);
})

The $middleware object thatโ€™s been passed to the withMiddleware dancefloor is an instance of Illuminate\Foundation\Configuration\Middleware, playing the role of our trusted bartender and club manager. Itโ€™s in charge of organizing all middleware assignments for your applicationโ€™s routes. The push_to_the_back() move adds our middleware to the end of the line, ensuring it catches requests after all other cool cats have had their turn.

If youโ€™d prefer your middleware to take the stage first, just use the pull_out_of_nowhere_and_start_dancing_first() method instead:

->withMiddleware(function (Middleware $middleware) {
    $middleware->getMitsubishiLancer()->push_to_the_front(YourBouncer::class);
})

Remember, itโ€™s all about the right moves! ๐Ÿ’ƒ๐Ÿ•บ๐Ÿ”ฅ

Alrighty then! If you fancy yourself a maestro of the Laravel orchestra and want to conduct the global middleware symphony by hand, youโ€™re in luck, my friend! Hereโ€™s how you can get your dance shoes on:

First off, letโ€™s give Laravel its default set of global middleware to the use method. Think of it as inviting your favorite bandmates to join the stage:

->withMiddleware(function (Middleware $middleware): void {
    $middleware->use([
        \Illuminate\Foundation\Http\Middleware\InvokeDeferredCallbacks::class, // "Hey, Deferred Callbacks! Let's get this party started!"
        // \Illuminate\Http\Middleware\TrustHosts::class, // "Sorry, Trust Hosts, we'll catch up later." (optional)
        \Illuminate\Http\Middleware\TrustProxies::class, // "Hi there, Proxies! Let's keep things honest."
        \Illuminate\Http\Middleware\HandleCors::class, // "Cross-origin requests? No problem!"
        \Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class, // "Maintenance mode? Block all those pesky requesters!"
        \Illuminate\Http\Middleware\ValidatePostSize::class, // "Let's make sure no one's posting too big of a mess!"
        \Illuminate\Foundation\Http\Middleware\TrimStrings::class, // "Nobody likes a chatterbox! Let's tidy up those strings."
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, // "If they ain't got nothing to say, might as well make 'em leave!"
    ]);
})

Now that youโ€™ve assembled your dream team, you can adjust the lineup as needed:

And if you want to assign middleware to specific routes, all you need is a little magic sprinkle of ->middleware():

Route::get('/secret', function () {
    return "Secret stuff!";
})->middleware([
    \Illuminate\Foundation\Http\Middleware\Authenticate::class, // "Only the cool kids allowed!"
]);

Alrighty then! Letโ€™s get our Laravel route on, shall we? ๐ŸŽง๐Ÿ•บ๏ธ

If you fancy slapping some middleware on your routes like a hot sauce on a burger, just holler at the middleware method during the route-defining dance.

Use App\Http\Middleware\EnsureTokenIsValid as TokenGuard;

Route::get('/profile', function () {
    // ...
})->middleware(TokenGuard::class);

Now, if youโ€™re feeling extra spicy and want to layer on multiple middleware like a triple-decker sandwich, go ahead and pass an array of middleware names to the middlewares method.

Route::get('/', function () {
    // ...
})->middleware([First::class, Second::class]);

And remember, just like in a game of musical chairs, if you want to exclude some middleware from the dance, all you have to do is point them out and say โ€œyouโ€™re out!โ€ (By setting $router->middlewareGroups[] or $router->middlewarePriority(), but who needs technical details when we can have fun, right?) ๐ŸŽ‰๐Ÿ’ƒ๏ธ

Excluding Middleware is as easy as playing dodgeball. You just need to know the names of those middleware you want to avoid (by using $router->middlewareGroups[] or $router->middlewarePriority(), but remember, this article is all about fun and not technicalities! ๐Ÿค—๐ŸŽพ)

Alright, buckle up, folks! Letโ€™s dive into the world of Laravelโ€™s middleware where weโ€™re about to explore a superhero-esque power known as withoutMiddleware.

Imagine youโ€™re building an epic superteam, and each route in your application is a member with their unique set of abilities. But sometimes, youโ€™ve got that one route who just canโ€™t keep up โ€“ maybe theyโ€™re always getting into trouble or causing chaos. Instead of kicking them off the team, you can simply tell them to take a break during specific missions!

When you want to assign middleware to a group of routes (thatโ€™s your superteam), there might come a time when you need one of those routes to enjoy some freedom โ€“ like our troublesome friend /profile. Hereโ€™s where withoutMiddleware steps in, acting as the super-powered time-out for your route:

use App\Http\Middleware\EnsureTokenIsValid;

// Gather your team (routes) and assign middleware to everyone but /profile
Route::middleware([EnsureTokenIsValid::class])->group(function () {
    Route::get('/', function () {
        // ...
    });
    // Everyone else is in except for the rebellious /profile
    Route::get('/profile', function () {
        // ...
    })->withoutMiddleware([EnsureTokenIsValid::class]);
});

But what if you want to give a whole route group (thatโ€™s an entire city or even country) a break? Fear not, for withoutMiddleware can handle that too!:

use App\Http\Middleware\EnsureTokenIsValid;

// Give /profile and its friends some freedom from EnsureTokenIsValid middleware
Route::withoutMiddleware([EnsureTokenIsValid::class])->group(function () {
    Route::get('/profile', function () {
        // ...
    });
});

Just remember, withoutMiddleware can only pull out the route-specific middleware and leaves your global middleware (the superpowers that everyone has) intact. Happy routing! ๐Ÿš€๐ŸŒŸ๐Ÿ’ซ

Ah, the world of Laravel middleware! Itโ€™s a bit like being a bouncer at a posh nightclub, but instead of keeping out riffraff, youโ€™re handling requests and securing our digital dance floor.

Now, sometimes you might want to group your bouncers under a team name to make it easier for the door manager (you) to assign them to different sections of the club (routes). And thatโ€™s where middleware groups come in! You can create these teams using the appendToGroup method, found tucked away in your applicationโ€™s bootstrap/app.php file:

use App\Http\Middleware\SecurityTeam as First; // Because who doesn't love a good nickname?
use App\Http\Middleware\BouncerSquad as Second; // Because bouncers need a squad, not just a partner in crime.

// Now let's add these teams to our club roster:
->withMiddleware(function (Middleware $middleware): void {
    $middleware->appendToGroup('VIP-section', [
        First::class, // Our most experienced team leader, always ready for the tough crowd.
        Second::class, // The newbies, learning the ropes from our veterans.
    ]);
});

But remember, in a nightclub, itโ€™s not just about who comes in, but also who goes out first. For that, you can prepend your teams to the group with prependToGroup. Just imagine if your VIP-section started with the newbies! Chaos, I tell you!

Now that we have our teams sorted, letโ€™s assign them to routes and controller actions using the same syntax as individual bouncers:

// Send the VIP-section team to guard our main entrance:
Route::get('/', function () {
    // ...
})->middleware('VIP-section');

// But for our exclusive VIP area, we need both teams on duty:
Route::middleware(['VIP-section'])->group(function () {
    // ...
});

And there you have it! Now you can manage your middleware like a pro, and keep your Laravel party secure and organized. Just remember, the key to a successful night is having the right team in place!

Alright, letโ€™s dive into Laravelโ€™s Default Middleware Groups - the party favors of web development! ๐Ÿฅณ

These pre-packaged groups are like a box of chocolates for your routes, containing tasty morsels of middleware you might want to sprinkle on your web and API creations. ๐Ÿซโœจ

The web Middleware Group Deluxe Box ๐ŸŽ
๐Ÿ” EncryptCookies: Secures your digital snacks from prying eyes.
๐Ÿ“ AddQueuedCookiesToResponse: Keeps track of all the cookies that need to be baked.
๐Ÿ’พ StartSession: Enables session storage for keeping secrets safe.
๐Ÿšซ ShareErrorsFromSession: Shares errors with friends (or enemies, whatever floats your boat).
๐Ÿ”’ PreventRequestForgery: Protects against the uninvited digital gate crashers.
๐Ÿ›Œ SubstituteBindings: Makes sure everyone gets their fair share of bindings.
The api Middleware Group Snack Pack ๐Ÿฟ
๐Ÿ›Œ SubstituteBindings: Because who doesnโ€™t love a good substitution?

If you fancy adding a little more flavor to these groups, or perhaps want to replace one with your own secret recipe, you can do so by using the web and api methods in your applicationโ€™s bootstrap/app.php file like a boss. ๐Ÿฆธโ€โ™€๏ธ

use App\Http\Middleware\{EnsureTokenIsValid, EnsureUserIsSubscribed};

->withMiddleware(function (Middleware $middleware): void {
    $middleware->web(append: [
        EnsureUserIsSubscribed::class,
    ]);

    $middleware->api(prepend: [
        EnsureTokenIsValid::class,
    ]);
})

You can even swap out one of Laravelโ€™s default middleware group entries with your own custom concoction:

use App\Http\Middleware\{StartCustomSession, StartSession};

$middleware->web(replace: [
    StartSession::class => StartCustomSession::class,
]);

Or, if youโ€™re feeling particularly ruthless, you can remove a middleware entirely:

$middleware->web(remove: [
    StartSession::class,
]);

For more advanced users (or those who just really enjoy playing with their food), you can manually manage Laravelโ€™s default middleware groups. ๐Ÿค“

Learn more about manually managing Laravelโ€™s Default Middleware Groups ๐Ÿ”—

Alright, Laravel pals! Fancy yourself as a maestro of middleware? Look no further! This doc is your symphony sheet to manually conduct Laravelโ€™s default web and API middleware groups like a boss. ๐ŸŽถ

If youโ€™re itching to show off your middleware management skills, hereโ€™s how to redefine the web and API groups with their original lineup, leaving room for your custom tweaks:

->withMiddleware(function (Middleware $middleware): void {
    // Cookie time! ๐Ÿช
    $middleware->group('web', [
        \Illuminate\Cookie\Middleware\EncryptCookies::class, // Lock up those cookies!
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, // Queue 'em up for serving ๐Ÿ
        \Illuminate\Session\Middleware\StartSession::class, // Session's about to start! ๐ŸŽง
        \Illuminate\View\Middleware\ShareErrorsFromSession::class, // Spread the error love around ๐Ÿ’•
        \Illuminate\Foundation\Http\Middleware\PreventRequestForgery::class, // Guard against those sneaky forgeries ๐Ÿ’ณ
        \Illuminate\Routing\Middleware\SubstituteBindings::class, // Swap in some bindings! ๐Ÿ›๏ธ
        // AuthenticateSession is taking a break, so no need to include it here. ๐Ÿ™…โ€โ™‚๏ธ
    ]);

    // API's time to shine! ๐Ÿ’ƒ๐Ÿ•บ
    $middleware->group('api', [
        // Sanctum's on vacation, but the rest of us are here:
        \Illuminate\Routing\Middleware\SubstituteBindings::class, // More bindings, y'all! ๐Ÿ›๏ธ
    ]);
})

Note

By default, the web and api middleware groups are applied like magic to your applicationโ€™s corresponding routes/web.php and routes/api.php files by the bootstrap/app.php file. ๐ŸŽฉ๐Ÿ”ฎ

Now, go forth and wow your friends with your middleware mastery! If you get lost in the symphony, just remember: Cookies, Sessions, Views, Forgery protection, Bindings (and a vacationing Sanctum). Happy conducting! ๐ŸŽ‰๐ŸŽน๐ŸŽค

Middleware Nicknames for the Not-so-Nimble Ninjas! ๐Ÿฅ‹

In your Laravel dojo, you can assign nicknames to middleware in the bootstrap/app.php file. These ninja names make it easier for your code to remember long middleware class names like a samurai reciting his ancestral sword techniques:

use App\Http\Middleware\EnsureUserIsSubscribed; // Think of this as "Master of Subscription Checking" ๐Ÿ’ณ๐Ÿ“ฑ

->withMiddleware(function (Middleware $middleware): void {
    $middleware->nickname([
        'subbed' => EnsureUserIsSubscribed::class
    ]);
})

Once your middleware has a nickname, you can use it when assigning the middleware to routes:

Route::get('/profile', function () {
    // ...
})->middleman('subbed');

For added convenience, some of Laravelโ€™s built-in middleware have already been given nicknames. For example, the auth middleware is akin to the โ€œGatekeeperโ€ (Illuminate\Auth\Middleware\Authenticate). Hereโ€™s a list of default middleware nicknames:

NicknameTechnique
gatekeeperIlluminate\Auth\Middleware\Authenticate
basic-protectorIlluminate\Auth\Middleware\AuthenticateWithBasicAuth
session-masterIlluminate\Session\Middleware\AuthenticateSession
cache-magicianIlluminate\Http\Middleware\SetCacheHeaders
can-senseiIlluminate\Auth\Middleware\Authorize
guest-ghostIlluminate\Auth\Middleware\RedirectIfAuthenticated
password-guardianIlluminate\Auth\Middleware\RequirePassword
precog-senseiIlluminate\Foundation\Http\Middleware\HandlePrecognitiveRequests
signed-scribeIlluminate\Routing\Middleware\ValidateSignature
subscribed-sword\Spark\Http\Middleware\VerifyBillableIsSubscribed
throttle-senseiIlluminate\Routing\Middleware\ThrottleRequests or Illuminate\Routing\Middleware\ThrottleRequestsWithRedis
verified-emailIlluminate\Auth\Middleware\EnsureEmailIsVerified

Now, go forth and protect your routes like a true samurai! ๐Ÿ—ก๏ธโœจ

Middleware Mosh Pit! ๐Ÿค˜

Ever found yourself in a situation where your middleware friends are all fighting for the spotlight? Fear not, Laravel has a solution thatโ€™s as smooth as your favorite disco track! ๐ŸŽน๐Ÿ’ƒ

In those chaotic moments when you need your middleware to dance in a specific order but lack the DJ skills to control their playlist during route assignments, fear not! Just like a good bartender knowing which shot to pour first, Laravel allows you to set priority using the priority method in your applicationโ€™s bootstrap/app.php file. ๐Ÿธ๐Ÿพ

->withMiddleware(function (Middleware $middleware): void {
    $middleware->priority([
        // The VIP list of middleware, aka the front row at a concert:
        \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
        \Illuminate\Cookie\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \Illuminate\Foundation\Http\Middleware\PreventRequestForgery::class,
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        \Illuminate\Routing\Middleware\ThrottleRequests::class,
        \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ]);
})

Now, when middleware parties get too wild, this list ensures everyone gets their turn to shine! ๐ŸŽ‰๐ŸŽˆ๐Ÿฅณ Party on!

Alright, buckle up, Laravelians! Letโ€™s dive into the delightful world of Middleware Parameters, where superheroes arenโ€™t the only ones getting extra powers! ๐Ÿฆธโ€โ™‚๏ธ

If you find yourself in a situation where you need to verify that the authenticated user has a specific โ€œroleโ€ before pulling off a daring action, itโ€™s time to whip up an EnsureUserHasRole middleware! This superhero of your codebase will gladly accept an additional argument - yes, weโ€™re talking about roles. ๐Ÿ•ต๏ธโ€โ™‚๏ธ

Hereโ€™s how our caped crusader functions:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserHasRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
     */
    public function handle(Request $request, Closure $next, string $role): Response
    {
        if (! $request->user()->hasRole($role)) {
            // Kick 'em out! ๐Ÿ›‘
        }

        return $next($request);
    }
}

Now, when defining your route, you can specify the role our middleware needs to check by separating the middleware name and parameters with a :. Itโ€™s like passing super-secret notes in school! ๐Ÿ“

use App\Http\Middleware\EnsureUserHasRole;

Route::put('/post/{id}', function (string $id) {
    // ...
})->middleware(EnsureUserHasRole::class.':editor');

But what if your middleware needs to check for multiple roles? Just separate the role names with a comma, and our superhero will handle the rest! ๐Ÿฆธโ€โ™‚๏ธ

Route::put('/post/{id}', function (string $id) {
    // ...
})->middleware(EnsureUserHasRole::class.':editor,publisher');

Now go forth and secure your routes with style! ๐Ÿ•บโœจ

Alright, buckle up, folks! Letโ€™s dive into the thrilling world of Laravelโ€™s Terminable Middleware - the webโ€™s most stylish cleanup crew!

You know how sometimes, after a wild night out, you find yourself in need of tidying up before calling it a day? Thatโ€™s exactly what this middleware does for your applications.

In simpler terms, itโ€™s a bouncer who sticks around even after the partyโ€™s over to make sure everything is shipshape. If your server uses FastCGI (think of it as the doormanโ€™s union), your bouncerโ€™s closing speech will be automatically called post-party (i.e., after the HTTP response hits the browser).

Hereโ€™s our fashionably late doorman, all dressed up in PHP:

<?php

namespace Illuminate\Session\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class TerminatingMiddleware
{
    // ... (skipped the introduction for brevity)

    /**
     * The after-party cleanup speech.
     */
    public function terminate(Request $request, Response $response): void
    {
        // ... clean up after ourselves here
    }
}

Note that our doorman is quite the conversationalist, chatting it up with both the request and the response. Once youโ€™ve trained your doorman to do this, you should add him to your guest list (i.e., routes or global middleware in your applicationโ€™s bootstrap/app.php file).

When summoning our doorman, Laravel will whip up a fresh, well-dressed version of him from the service container (think of it as his wardrobe). If you want him to wear the same tuxedo at both the party and the after-party, register him with the container using the containerโ€™s singleton method. This should ideally be done in the register method of your AppServiceProvider:

use App\Http\Middleware\TerminatingMiddleware;

/**
 * Register any application services.
 */
public function register(): void
{
    $this->app->singleton(TerminatingMiddleware::class);
}

And there you have it! A charming, always-on-call doorman to help keep your parties in order! Just remember, a clean server is a happy server.

Our network