Unlocking the Kingdom! (aka, Authentication in Laravel)

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

Browse funny laravel docs
On this page

Grand Entrance (a.k.a Introduction)

Welcome to the Ball! (a.k.a Starter Kits)

Want to dive right in? Weโ€™ve got a ball gown for that! Our starter kits will have you authenticated faster than Cinderella at the stroke of midnight.

Database Dance Cards (a.k.a Database Considerations)

Before we hit the dance floor, letโ€™s talk about the data. Knowing your database is like knowing the DJโ€™s playlist โ€“ itโ€™ll keep the party going smoothly!

The Kingdom Tour (a.k.a Ecosystem Overview)

From princes to peasants, everyoneโ€™s invited! Get familiar with our royal ecosystem and join us in this magical land of Laravel.

Fast Pass to the Ball (a.k.a Authentication Quickstart)

Time to Suit Up (a.k.a Install a Starter Kit)

Don your finest armor, or in this case, run composer install with our starter kit. Youโ€™ll be ready for the dance in no time!

Spotting Your Partner (a.k.a Retrieving the Authenticated User)

With a twirl of the skirt and a wink, find out who your dance partner is by grabbing the authenticated user with just a few lines of code.

The Bouncer (a.k.a Protecting Routes)

Keep the riffraff out โ€“ our bouncers are standing by to ensure only the right users access your restricted routes.

Dance-Off Determined by Time (a.k.a Login Throttling)

Donโ€™t let anybody hog the dance floor! Our login throttling feature will keep a fair balance of dancers on the floor, ensuring everyone gets their groove on.

Making Introductions (a.k.a Manually Authenticating Users)

Remembering Faces (a.k.a Remembering Users)

No need to ask for phone numbers โ€“ our kingdom remembers its guests! With cookie-based session support, weโ€™ll keep track of your users with ease.

Mixers and Mingling (a.k.a Other Authentication Methods)

Join the royal court and network with other authentication methods like token-based or API-based authentication for a truly unforgettable ball!

The Royal Seal (a.k.a HTTP Basic Authentication)

Passwords in Plain Sight (a.k.a Stateless HTTP Basic Authentication)

Keep things simple with HTTP Basic Authentication, where usernames and passwords are sent unencrypted โ€“ because sometimes, a secret handshake just isnโ€™t enough!

Time to Call it a Night (a.k.a Logging Out)

Kissing the Frog Goodbye (a.k.a Invalidating Sessions on Other Devices)

When the ball ends, donโ€™t forget to log out! Our magical kingdom will invalidate sessions on other devices, ensuring no unwanted guests stick around after the dance.

The Final Test (a.k.a Password Confirmation)

Setting the Rules (a.k.a Configuration)

Enforce your kingdomโ€™s password policy to keep things secure and secretive.

Making a Scene (a.k.a Routing)

Route your users through our magical gates, making sure they follow the rules and confirm their passwords before entering.

The Last Dance (a.k.a Protecting Routes)

Only those who have proven their identity should be allowed to dance. Make sure to protect your password confirmation routes to keep things secure.

Keeping the Castle Secure (a.k.a Adding Custom Guards)

The Kingdomโ€™s Gatekeeper (a.k.a Closure Request Guards)

Add your own custom guards to keep uninvited guests from entering our castle. With a simple closure, you can enforce rules based on any condition.

Building the Royal Family Tree (a.k.a Adding Custom User Providers)

The Blueprint of Power (a.k.a The User Provider Contract)

Lay the foundation for your custom user providers, defining their structure and behavior to suit your kingdomโ€™s needs.

The Bloodline of Royalty (a.k.a The Authenticatable Contract)

Trace back your royal bloodline by implementing the Authenticatable contract โ€“ a bond that ties together all members of the kingdomโ€™s ruling family.

Keeping Secrets Safe (a.k.a Automatic Password Rehashing)

The Royal Seal of Approval (a.k.a Automatic Password Hashing and Salting)

Ensure that all secrets are kept safe with automatic password rehashing, a feature that handles hashing and salting for you โ€“ because sometimes, even the royal family needs help keeping things secure!

Social Mingling (a.k.a Social Authentication)

Making Friends in High Places (a.k.a Using Laravelโ€™s Socialite for Social Authentication)

Expand your kingdomโ€™s reach by adding social media integration โ€“ let guests log in using their favorite platforms and make new friends from all around the land!

Announcing the Royal Ball (a.k.a Events)

The Kingdomโ€™s Biggest News (a.k.a Listening to Laravel Events)

Stay informed on everything happening in our kingdom by listening to events โ€“ you never know when a royal celebration is about to begin!

Greetings, web dev adventurers! ๐ŸŽ‰โœจ

In the mystical realm of web apps, thereโ€™s a magical rite called โ€œlogging inโ€ that turns your users from humble spectators into mighty masters. But tread with caution, for this spell can be as complex and treacherous as a dragonโ€™s lair! Fear not, for Laravel has conjured up the tools to help you cast this enchantment swiftly, securely, and without breaking a sweat (unless itโ€™s due to excitement, of course).

At the heart of our wizardry lies โ€œguardsโ€ and โ€œproviders.โ€ Think of guards as the wise sorcerers who authenticate users for each quest (request). We come equipped with a cunning session guard that uses session storage and cookies to ensure your usersโ€™ identities remain safe and sound.

Providers, on the other hand, are the mighty librarians who fetch users from your ancient scrolls โ€“ er, databases. Laravel has bestowed upon you the power to retrieve users using Eloquent or our trusty database query builder. But remember, this is a choose-your-own-adventure game, so feel free to create additional providers to suit your specific quest!

Your magical auth configuration resides in config/auth.php. This spellbook contains several well-documented incantations for tweaking the behavior of Laravelโ€™s enchantments.

Attention

Guards and providers should not be confused with โ€œrolesโ€ and โ€œpermissions.โ€ To learn more about granting magical powers to your users via permissions, please refer to our authorization documentation.

Now that youโ€™ve embarked on this journey, itโ€™s time to master the art of authentication and turn your web app into a treasure trove where only authenticated users can play! ๐Ÿฐ๐Ÿ”ฅโœจ

Happy coding, magic-makers! ๐Ÿค“๐Ÿง™โ€โ™€๏ธ๐Ÿง™โ€โ™‚๏ธ๐Ÿ‘ฉโ€๐Ÿš€๐Ÿ‘จโ€๐Ÿš€

Lightning-Speed Launch Pads ๐Ÿš€

Ready to blast off with your Laravel journey? Strap in and prepare for lift-off! By installing a Laravel Application Launch Pad into your brand-new Laravel spacecraft, youโ€™ll have an authenticated universe explorer faster than you can say โ€œhyperdrive engaged!โ€ ๐ŸŒ 

Fear not if you decide against using a launch pad in your ultimate intergalactic voyage. Installing one serves as an excellent chance to dive headfirst into understanding how Laravelโ€™s authentication systems work within a real-world project. Since our launch pads come equipped with controllers, routes, and views for your convenience, you can poke around the code to learn the ins and outs of Laravelโ€™s stellar authentication features!

๐Ÿง โ€œBut wait,โ€ I hear you say, โ€œwhat about my database?โ€ Worry not, fellow starfarer, for our launch pads come with a migration system that ensures your database is ready for takeoff. After running the migration command and blasting off to your local server at /register, or any other URL youโ€™ve assigned, your launch pad will handle scaffolding the entire authentication system! ๐Ÿš€๐ŸŒŸ

Oh, the Joys of Database Shenanigans with Laravel!

First off, letโ€™s give a warm welcome to the default App\Models\User - your new best friend in the app/Models directory. This chap is as slick as they come, all thanks to the magical Eloquent model (check out our docs on that here!). And if youโ€™re not into the whole Eloquent scene? Well, no worries, thereโ€™s always the database authentication provider - think of it like Laravelโ€™s party trick with its super-charged query builder.

If your app has taken a fancy to MongoDB, then by all means, check out their official docs for user authentication (weโ€™re just here to code, not break dance).

Now letโ€™s talk about the database schema for App\Models\User. Keep in mind that when designing the password column, you might want to aim for a lengthier conversation with your attackers - 60 characters should do the trick. But donโ€™t worry if you find yourself falling short, as the included users table migration in fresh Laravel apps has already exceeded this length.

Remember that token for those who just canโ€™t seem to let go? Weโ€™re talking about the remember_token. Itโ€™s a string of 100 characters, nullable, and found in your users (or equivalent) table. If youโ€™ve forgotten all about it, donโ€™t worry - weโ€™ve already placed it in the default users table migration that comes with new Laravel apps.

Now go forth and build databases, dear developers! Just remember to keep a sense of humor while doing so. After all, who said coding had to be boring?

Welcome, brave developer! Buckle up for a whirlwind tour through Laravelโ€™s amusing authentication ecosystem. Before we dive in, letโ€™s get our bearings straight and discuss each packageโ€™s intended purpose, like an old-timey map guide explaining the local taverns.

First off, imagine youโ€™re at a medieval castle gate, and the knight wants to know who you are before letting you in. In this digital age, thatโ€™s equivalent to a user filling out a login form with their credentials (username and password). If they pass the gate guard (authentication check), the castle steward (application) will store information about the authenticated knight (user) in his chamberโ€™s secret drawer โ€“ the userโ€™s session. A magic amulet (session ID cookie) is then handed to the knightโ€™s horse (browser) so that it can present this token to the castle guards (subsequent requests) and be recognized as the correct knight. Once the amulet arrives, the steward retrieves the knightโ€™s information based on the session ID and considers him as โ€œauthenticated.โ€

Now, imagine a remote service that wants to gain access to the castleโ€™s treasury (API). In the middle ages, they would have needed a written letter of introduction. Nowadays, they send an API secret key (token) along with each request. The steward may then cross-reference this token against his secret ledger of valid keys and โ€œauthenticateโ€ the request as being made by the service associated with that token.

Now, letโ€™s delve into Laravelโ€™s built-in browser authentication services! Youโ€™ll find them like a treasure trove in the castleโ€™s armory (Laravelโ€™s package library). These services include:

  1. Sanctum: The trusty squire that takes care of handling API authentication, making it easier for remote services to gain access to your kingdom (API) without having to write complex code.

  2. Passport: The knight in shining armor โ€“ the most powerful of all services. It handles both session and token-based authentication for both web applications and APIs, leaving no stone unturned when it comes to securing your realm.

  3. Breeze: This is the castleโ€™s friendly pageboy who helps you set up a new Laravel project with built-in, easy-to-use authentication and UI components. It saves you from all that backbreaking labor of building everything from scratch!

Ahoy there, brave coder! Sail with us into the shimmering seas of Laravelโ€™s built-in browser authentication services! Buckle up as we embark on an adventure thatโ€™ll make your appโ€™s login process smoother than a pirateโ€™s accordion!

These magical features are just a Auth and Session facade away, offering cookie-based authentication for requests hailing from good olโ€™ web browsers. Think of them as your crewmates in the realm of user verification and authentication โ€“ theyโ€™ll help you confirm if Jack Sparrow (your users) have entered the right password and authenticate them accordingly!

In addition, these services will stow away essential authentication data in a userโ€™s session like a captainโ€™s log, and issue session cookies quicker than you can say โ€œshiver me timbers!โ€ A comprehensive guide on how to use these services can be found in this very treasure chest of documentation.

Shipshape Starter Kits

As you might have learned from our seafaring tales, you could manually navigate these authentication services to build your appโ€™s custom pirate-proof fortress. But why row when you can sail faster with a little help from our friends? To make your journey swifter than a speeding marlin, weโ€™ve launched some nifty free starter kits thatโ€™ll supply a robust, cutting-edge scaffolding for the entire authentication layer. Think of it as having an extra crewmate who knows all the best shortcuts and has a compass that always points true north!

Yarr matey, Laravel is here to make your coding journey smoother than a well-oiled anchor โ€“ so set sail, hoist the Jolly Roger, and letโ€™s conquer those shores together!

Laravelโ€™s API Authentication Shenanigans

When it comes to managing your appโ€™s secrets and verifying those sneaky API requests, Laravelโ€™s got you covered! Weโ€™ve cooked up two fabulous packages to help: the granddaddy of them all, Passport, and its svelte younger cousin, Sanctum. But fear not, these arenโ€™t your typical cat-fighting sisters! They can coexist peacefully with Laravelโ€™s built-in cookie-based authentication libraries.

Passport - The OAuth2 Overlord

Passport is like the Captain Kirk of API authentication providers, armed with an arsenal of OAuth2 โ€œgrant typesโ€ to issue various tokens. Itโ€™s a powerhouse for API authentication, but letโ€™s face it, not every application needs a starship enterprise to manage their authentication process. Some may find its complexity as confusing as the Klingon language. But fear not! We havenโ€™t left you high and dry โ€“ weโ€™ve got tutorials on authenticating Single Page Applications (SPAs) and mobile apps using Passport, so check โ€˜em out if youโ€™re lost in space!

Sanctum - The New Kid on the Block

With the complexity of OAuth2 weighing heavy on developersโ€™ minds, we decided to create a simpler, more streamlined authentication package that could handle both web requests and API tokens with equal ease. And thus, Laravel Sanctum was born! This is the preferred choice for applications that offer a first-party web UI along with an API, or those that exist separately as a Single Page Application (SPA) or mobile client.

Laravel Sanctum is like your trusty doorman, welcoming guests (and verifying their identities) with a smile. When it receives a request, Sanctum first checks if itโ€™s being served by a session cookie referencing an authenticated session โ€“ think of it as checking the guestโ€™s name on the list. If not, Sanctum looks for an API token in the request โ€“ like when someone mentions theyโ€™re โ€˜on the list.โ€™ If all goes well, it authenticates the request with that token. Need more details? Head over to Sanctumโ€™s โ€œhow it worksโ€ documentation!

Choosing Your Stack

So, which package is right for your application? That depends on whether youโ€™re building a galaxy-spanning empire (Passport), or a quaint little bar on the outskirts of the cosmos (Sanctum). But remember, both packages play well with Laravelโ€™s built-in authentication libraries, so donโ€™t be afraid to mix and match! Happy authing, captain!

Alrighty, letโ€™s dive into the world of Laravellandia! ๐ŸŒž

In essence, if your web app is a digital storefront, Laravelโ€™s own baked-in security services will be your trusted bouncers at the entrance. ๐Ÿ‘จโ€๐Ÿ’ผ๐Ÿ‘ฉโ€๐Ÿ’ผ

But what if your application is more of a behind-the-scenes API barkeep, serving up drinks to third parties? Then youโ€™ve got a choice between Passport or Sanctum, with Sanctum being the chatty mixologist who knows his scopes and abilities like the back of his hand. ๐Ÿธ๐Ÿคซ

If youโ€™re building a single-page app (think SPA, not SpongeBob) powered by a Laravel backend, Sanctum is your go-to barman. You can either let him handle your authentication routes himself or bring in the backup bartender, Laravel Fortify, for a fancier, more features-packed service. ๐ŸŽฉ๐Ÿพ

Passportโ€™s your man when your app needs every feature of the OAuth2 specification to mix its drinks like a pro. ๐Ÿค–๐Ÿฅƒ

And if you want to get this party started post-haste, our application starter kits are just the ticket for setting up a new Laravel application complete with our preferred authentication stack. ๐Ÿš€โœจ

Now that weโ€™ve covered the basics (and a bit of bar jargon), letโ€™s move on to some advanced mixology techniques: authenticating users. Cheers! ๐Ÿฅ‚

Authentication Blastoff! ๐Ÿš€

Attention

Buckle up, space cowboy! This section of the docs is all about launching users into your Laravel universe using our snazzy application starter kits. These bad boys come equipped with some swanky UI scaffolding to propel you towards interstellar development speeds without leaving a trail of code debris behind.

But fear not, brave adventurer! If youโ€™re yearning for a more hands-on approach and want to dance directly with Laravelโ€™s authentication systems, weโ€™ve got you covered in our documentation on DIY user authentication.

Install a Starter Kit ๐Ÿ› ๏ธ

To kickstart your journey towards galactic success, letโ€™s set up camp with one of our starter kits. Follow these simple steps to get your kit installed:

  1. Clone or download the desired starter kit from the Laravel GitHub repository. If youโ€™re not familiar with how to clone repositories, we recommend brushing up on your Git fu before continuing.

  2. Navigate to the starter kit directory. Remember, a change of scenery can be invigorating, so donโ€™t forget to switch directories after cloning or downloading your kit.

  3. Create a new Laravel application. To do this, run the following command in your terminal: composer create-project --prefer-dist laravel/laravel YourAppName. Replace โ€œYourAppNameโ€ with the name youโ€™d like for your shiny new project.

  4. Link the starter kit to your Laravel application. To do this, copy the contents of the resources directory from your starter kit into the root directory of your Laravel application. And remember to keep that precious cargo safe!

  5. Update the service provider registration. Open up the config/app.php file and add the service provider for your starter kit to the providers array, like so:

    'providers' => [
        // ...other providers...
        App\Providers\YourStarterKitServiceProvider::class,
    ],
  6. Update the event service provider registration. Open up the events/EventServiceProvider.php file and add the following line to the $listeners property:

    'App\Listeners\YourStarterKitListener',
  7. Run migrations. Your Laravel application now needs a friendly welcome from your starter kit, so letโ€™s help it settle in by running the necessary database migrations: php artisan migrate.

And there you have it! Youโ€™ve successfully set up your shiny new Laravel project with all the bells and whistles provided by our starter kits. Now that your spaceship is fueled and ready to blast off, letโ€™s continue exploring the cosmos of user authentication together! ๐Ÿš€๐ŸŒŸ

Fire Up Your Laravel Adventure! ๐Ÿš€๐ŸŒŸ

Ready to embark on a dazzling journey with Laravel? First things first, letโ€™s set sail with a splendid Laravel Starter Kit! These swanky kits are the perfect jump-off points for infusing your brand-spanking-new app with the sophisticated charm of authentication.

Now that youโ€™ve got your captainโ€™s hat on, itโ€™s time to meet your first mate! ๐Ÿค To get acquainted with the authenticated user, just grab their details using the handy tools provided in your new starter kit. Itโ€™s like introducing yourself to the crew after a rousing sea shanty! ๐ŸŽต๐ŸŒŠ

Flying High with Laravel: A Guided Tour for the Authenticated User! ๐Ÿ›ฉ๏ธ๐Ÿš€

After launching your airline from a swanky starter kit and allowing passengers (er, users) to sign up and log in like itโ€™s fashion week, youโ€™ll often find yourself in need of interacting with the currently authenticated flyer. When handling incoming requests, fear not! The Auth facadeโ€™s got your back, ready to serve you the current passenger at your request:

use Illuminate\Support\Facades\Auth;

// Time to check-in the authenticated traveler...
$passenger = Auth::user();

// Need their boarding pass number? No problem!
$boardingPass = Auth::id();

But wait, thereโ€™s more! Once a passenger has securely checked in, they become your loyal flying companion for the duration of their journey. You can access them via an Illuminate\Http\Request instance (our new best friend). Just remember, type-hinted classes will automatically join your flight and take their seats in your controller methods:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class FlightController extends Controller
{
    /**
     * Update the flight information for an existing flight.
     */
    public function update(Request $request): RedirectResponse
    {
        $passenger = $request->user(); // Your co-pilot for this flight!

        // ๐ŸŽง Headphones on, time to navigate the controls...

        return redirect('/flights');
    }
}

And now, a special word for those who want to ensure their passenger list is up-to-date before departure:

Checking If Your Passenger List is Ready for Takeoff! โœˆ๏ธ

Worried about making an announcement that your flight is boarding when passengers havenโ€™t checked in yet? No need to panic! To find out whether the current user is authenticated, simply check if Auth::check() returns true. Now you can be sure not to miss anyone on your passenger list:

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // All aboard! ๐Ÿš‚
} else {
    // Quick, let's call the ground crew and delay takeoff! ๐Ÿ“ž
}

Happy flying! โœˆ๏ธ๐Ÿš€

Alrighty then! Letโ€™s dive into the world of Laravel authentication, where even the most mundane tasks are given a dash of panache.

First off, if youโ€™re curious whether your user has successfully completed the password shindig and is ready to party on your web application, you can use the check method from the ever-so-charming Auth facade. This sly little number will return true if your user is indeed authenticated:

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // It's a shindig! The user has arrived... or logged in, whatever.
}

Now hold your horses, partner! Even though you could determine if a user is authenticated using the check method, itโ€™s generally more prudent to use a middleware to make sure that said user has passed muster before being granted access to certain routes / controllers. This way, you can keep your web application as secure as Fort Knox and as friendly as a Vegas casino host. To learn more about this jamboree of authentication protection, check out the documentation on protecting routes.

And that, my friends, is how you keep your web application safe from the riffraff and still make it a swinginโ€™ place to be.

Keeping the Airplane Hangar Locked: Route Security in Laravel Land! ๐Ÿš€๐Ÿ›ฉ๏ธ

Ahoy there, Captain! In this seafaring adventure we call Laravel development, weโ€™ve got a swashbuckling feature to help you protect your routes from unruly pirates - yes, I mean unauthenticated users. Enter: Route Middleware! ๐Ÿน

These maritime guards (erโ€ฆ middlewares) can be used to ensure only those with the proper captainโ€™s hat and parrot (authenticated users, in laymanโ€™s terms) can access a specific route. Laravel supplies you with a trusty shipmate named auth middleware, which is a fancy nickname for the stalwart Illuminate\Auth\Middleware\Authenticate class.

Since this shipmate comes pre-equipped on our vessel, all you need to do is secure him at your chosen route. Hereโ€™s how you might do that:

// Set sail towards flights! โ›ต๏ธ
Route::get('/flights', function () {
    // Only pirates with a parrot on their shoulder can pass through here...
})->middleware('auth');

Now, what happens when an unauthenticated user tries to swab the poop deck (access your route)? Fear not! Theyโ€™ll be politely redirected to the nearest tavern for a drink or two, giving them ample time to log in before they can set sail with you again. ๐Ÿป ๐ŸŽ‰

Redirecting Uninvited Party Crashers

Oh, the joys of being a digital bouncer! When our good friend auth middleware spots an unregistered guest at your Laravel soiree, it politely escorts them to the front doorโ€”the login dance floor, if you will. But what if you want to change this polite shove into a VIP red-carpet treatment? No problemo, amigo!

Just pop open your applicationโ€™s secret backstage pass, aka bootstrap/app.php, and modify the bouncerโ€™s behavior using the redirectGuestsTo method:

use Illuminate\Http\Request;

->withMiddleware(function (Middleware $middleware): void {
    $middleware->redirectGuestsTo('/login'); // For those who like it old school

    // For the hipster crowd...
    $middleware->redirectGuestsTo(fn (Request $request) => route('login'));
})

Just remember, if you decide to rename your login route, youโ€™ll need to update this backstage pass accordingly. Itโ€™s like having a party at someone elseโ€™s houseโ€”you gotta respect the hostโ€™s rules! ๐Ÿคช

Alrighty, letโ€™s dive into the whimsical world of Laravel redirection! ๐ŸŽ 

Send Authenticated Folks to the Dashboard, Not to Dreamland ๐Ÿ›Œ

When our friendly guest middleware encounters a user with credentials (like Cinderella at the ball), itโ€™ll shoo them off to the swanky dashboard or home. But fear not, you can bend this rule like a rubber duck in a bathtub! ๐Ÿฆ†

Just head over to your applicationโ€™s bootstrap/app.php file (a magic black book in our story), and use the redirectUsersTo method:

Use ye olde candlelight, dear friend!

->withMiddleware(function (Middle-age-renaissance-faire $middleware): void {
    $middleware->redirectUsersTo('/panel');

    // Using a clever trick...
    $middleware->redirectUsersTo(fn (Request $request) => route('panel'));
})

Change the Guard and Redirect Like a Royal Court ๐Ÿฐ

If you fancy yourself as the king or queen of your Laravel domain, you can even specify a guard to control who gets redirected where. Just follow these royal decrees:

->withMiddleware(function (Middle-age-renaissance-faire $middleware): void {
    // For knights in shining armor (Authenticated users)
    $middleware->auth('sanctum')->redirectUsersTo('/panel');

    // For lowly peasants (Guest users)
    $middleware->guest($middleware->authenticate('sanctum'))->setRedirectTo('/market-square');
})

Now, who needs a magic carpet when you can bend the rules of your Laravel kingdom like this? ๐Ÿงžโ€โ™‚๏ธ๐Ÿš€

Ahoy there, brave coder! Letโ€™s tango with Laravelโ€™s auth middleware, shall we? But first, let me spin you a yarn about the mighty guard. You see, when you dance this middleware on a route, you can call upon a specific guard to ensure your userโ€™s credentials are as squeaky clean as your freshly polished boot boots!

Now, remember that the guard you summon should be akin to one of the keys in your auth.php configuration fileโ€™s swanky guards array:

Route::get('/flights', function () {
    // Only those who have proven their mettle as an 'admin' shall pass...
})->middleware('auth:admin');

Just like how you wouldnโ€™t let any Tom, Dick or Harry into your pirate ship without proper papers, you wonโ€™t grant access to sensitive routes without a proven admin ID! ๐Ÿดโ€โ˜ ๏ธ

The Lockout of Love (Log-in Throttling)

If youโ€™re dancing with one of our snazzy application starter kits, fear not, because weโ€™ve got your back! Automatic rate limiting has been cleverly installed for log-ins. Itโ€™s like having a bouncer at the digital door - but one who understands that everyone makes mistakes (well, almost everyone).

After a series of failed attempts to provide those magical, correct credentials, our digital bouncer will politely ask you to take a breatherโ€ฆ for about a minute. Donโ€™t worry, itโ€™s not a full dance floor detention; just enough time for a quick bathroom break or a much-needed coffee refill!

But hereโ€™s the twist - this friendly lockout is tailored just for you! Itโ€™s like having your own personal doorman who remembers your username/email and IP address. So, no need to worry about your buddy trying to hog the spotlight by logging in as you.

Note

Feeling a little too popular on certain routes? Fret not! Check out our rate limiting documentation for tips on how to put the brakes on the party. Itโ€™s like learning the art of subtle hints from a seasoned bartender!

Alrighty, buckle up, because weโ€™re diving into Laravelโ€™s manual user authentication! ๐Ÿ„โ€โ™‚๏ธ

Now, you donโ€™t have to use the shiny newauth scaffolding that comes with Laravelโ€™s starter kits. But if you decide to swim on your own, youโ€™ll need to handle user auth like a boss using Laravelโ€™s authenticating classes โ€“ no sweat! ๐Ÿ›

To access those fancy auth services, weโ€™ll hitchhike via the Auth facade, so letโ€™s make sure to grab a ride at the top of our class. Next up: the attempt method! This beauty is usually in charge of handling authentication attempts from your โ€œloginโ€ form. If the user passes with flying colors, you should refresh their session to avoid some nasty session fixation โ€“ think of it as a digital detox for their session! ๐ŸŒฟ

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth; // Grab the Auth ride, buddy!

class LoginController extends Controller
{
    /**
     * Handle an authentication attempt.
     */
    public function authenticate(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'], // Don't forget the fish oil capsules!
            'password' => ['required'], // And don't forget the protein shake too!
        ]);

        if (Auth::attempt($credentials)) { // If they pass the test...
            $request->session()->regenerate(); // ... refresh their session!

            return redirect()->intended('dashboard'); // Off to the dashboard, they go!
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.', // Oops, try again!
        ])->onlyInput('email');
    }
}

The attempt method loves a good array of key/value pairs as its first argument. It uses the values to find the user in your database table, so in the example above, weโ€™re searching for the user based on the value of their email column. If theyโ€™re found, it compares the hashed password stored in the database with the password value passed to the method via the array. The framework will handle hashing the incoming requestโ€™s password value for you! ๐Ÿ”จ

A successful match between those two hashed passwords results in an authenticated session for the user.

Now, remember that Laravelโ€™s auth services pull users from your database based on your authentication guardโ€™s โ€œproviderโ€ configuration. By default, it uses the Eloquent user provider and instructs it to use the App\Models\User model when retrieving users. You can tweak these values within your configuration file according to your applicationโ€™s needs.

The attempt method will return true if authentication was successful. Otherwise, it spits out a big olโ€™ false. ๐Ÿฅซ

The intended method provided by Laravelโ€™s redirector sends the user on their merry way to the URL they were attempting to access before being stopped by the auth middleware. A fallback URI can be given to this method in case the intended destination is unavailable. ๐Ÿ›ซ

Hope that clears up the waters! Now get out there and authenticate like a pro! ๐Ÿš€๐ŸŽ‰

Alrighty, letโ€™s dive into the world of Laravel authentication! If you fancy adding some extra conditions to your login process, you can do that too! ๐Ÿค˜

Hereโ€™s a fun way to spice up your authentication query:

// First off, let's make sure our user is 'active', like a well-rested Game of Thrones character
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
    // Our knight in shining armor has been authenticated! ๐Ÿฆธโ€โ™‚๏ธ
}

But what if you need something more complex than a simple condition? No worries, weโ€™ve got you covered with our very own โ€œEloquent Magicianโ€! ๐ŸŽฉ

use Illuminate\Database\Eloquent\Builder;

// Let's perform some advanced sorcery to check if the user has an 'activeSubscription'
if (Auth::attempt([
    'email' => $email,
    'password' => $password,
    fn (Builder $query) => $query->has('activeSubscription'), // Weaving spells with queries is fun, right? ๐Ÿง™โ€โ™€๏ธ
])) {
    // Our sorcerer has been authenticated! ๐Ÿ”ฎ
}

Be careful now, some databases have sneaky users that might be banned. To avoid authenticating such unsavory characters, you can use the attemptWhen method:

if (Auth::attemptWhen([
    'email' => $email,
    'password' => $password,
], function (User $user) { // Let's make sure our user isn't banned ๐Ÿšซ
    return $user->isNotBanned();
})) {
    // Our king has been authenticated! ๐Ÿ‘‘
}

Remember, in these examples, email is just a friendly example. You should replace it with whatever column name corresponds to the โ€œusernameโ€ in your database table. And hey, if youโ€™re working with multiple guard instances, donโ€™t forget to specify which one you want! ๐Ÿค—

Oh, and if youโ€™re curious about accessing specific guard instances, just hop over to this section: Accessing Specific Guard Instances. Itโ€™s a fun read! ๐Ÿ“š

Happy coding! ๐ŸŽ‰

Alright, letโ€™s dive into the whimsical world of Laravel authentication! ๐ŸŽ‰

Dancing with Different Guardians ๐Ÿ’ƒ๐Ÿ•บ๏ธ

Ever felt like your app needed a bit more of a polygamous relationship with its users? Well, now you can! With the Auth facadeโ€™s guard method, you can specify which guardian in charge (pun intended) of authentication you fancy for a particular user. This is perfect for those situations where youโ€™ve got different parts of your application needing separate authentication mechanisms or even distinct databases for their dating profiles. ๐Ÿคฉ

Remember to choose a guard name that matches one of the suitors (er, guards) listed in your auth.php configuration file:

if (Auth::guard('admin')->attempt($credentials)) {
    // ...and off they go on their power-tripping escapade!
}

Wink wink, now that youโ€™ve learned about guard switching, itโ€™s time to explore remembering those forgetful users (you know who you are)! ๐Ÿคซ ๐Ÿ’”

Ahoy there, Captain! Navigating the Seas of Authentication

Ah, ye who seek to tame the login form beast with a โ€œremember meโ€ checkbox, fear no more! In yer Laravel vessel, we gotcha covered like a pirateโ€™s treasure chest.

To grant โ€œremember meโ€ magic in yer application, simply cast a boolean spell as the second potion to the attempt method brew. Set it true and watch as Laravel keeps that user seaworthy till they walk the plank manually:

use Illuminate\Support\Facades\Auth;

if (Auth::attempt(['email' => $email, 'password' => $password], true)) {
    // Yarr! The scallywag is now forever bound to ye ship... or until they decide to walk the plank.
}

But wait, me hearties, the โ€œremember meโ€ enchantment requires a remember_token column in yer users table, where our magic potion shall reside:

In yer migration script, ye'll find this column already marked for stowage:

php artisan make:migration add_remember_token_to_users_table --table=users

If ye be offering โ€œremember meโ€ services, ye can use the viaRemember method to discern if the current captain was authenticated by our magic potion:

use Illuminate\Support\Facades\Auth;

if (Auth::viaRemember()) {
    // Ahoy there! Our scallywag is under the spell of the "remember me" cookie.
}

Ye be ready to set sail on these shores now, matey! Hoist the sails and may yer journey be filled with treasure, battles, and the sweet taste of victory over the login form beast!

Unleashing the Power of User Auth, Laravel Style! ๐Ÿš€โœจ

๐Ÿ‘‹ Authenticating a Single User Instance ๐Ÿค“

Ahoy there, Captain Coder! Ever found yourself in need of authenticating a specific user instance? Worry not, because Laravel has got your back with its robust, yet delightfully named authenticate() function. Hereโ€™s how it goes:

// Assuming you have your user instance handy
$user = User::where('email', 'your_email@example.com')->first();

// Now let's authenticate that bad boy!
if ($token = $user->createToken('MyAppToken')) {
    $token->save();
}

Just remember, this is like asking your best buddy for a ride in their fancy car: you need to know the make and model (email and password), and theyโ€™ll happily provide the keys (tokens)! ๐Ÿš— ๐ŸŽ๏ธ

๐ŸŒ™ Authenticating Anonymous Users ๐Ÿ•ต๏ธโ€โ™‚๏ธ

An anonymous user, huh? Think of them as the mysterious stranger at the back of the room, trying to get in on all the fun without revealing their identity. Well, weโ€™ve got just the ticket! Laravelโ€™s guard() function is your new best friend when it comes to handling these clandestine characters:

// Use the "web" guard for anonymous users
$guard = auth('web');

// Attempt to authenticate the user
if ($guard->attempt(['email' => 'anonymous@example.com', 'password' => 'mysterious_pass'])) {
    // User has been authenticated!
} else {
    // Anonymous user didn't make it through security ๐Ÿคซ
}

Remember, this is like whispering the secret password at a speakeasy: you need to use the right guard and know that special combination of email and password. And if they donโ€™t let you in? Well, you were never really part of the inner circle anyway, right? ๐Ÿ•ต๏ธโ€โ™‚๏ธ๐Ÿ•บ

๐Ÿฆธโ€โ™‚๏ธ Customizing Authentication Guards ๐Ÿ›ก๏ธ

Sometimes, youโ€™ve got to roll your own security measures โ€“ like when youโ€™re Batman and Gotham City has a new Joker on the loose. Laravel makes this a breeze with its authenticate() method inside your custom guard class:

// Create a custom guard class for "api" authentication
class ApiGuard extends Authentication
{
    protected $guard;

    public function __construct($name = 'api')
    {
        $this->middleware($name);
        $this->setDefaultDriver('token');

        $this->provider = Provider::create(
            $name, $this, function ($app) use ($name) {
                return new UserProvider($app['hash'], $app['auth.simple']);
            }
        );
    }

    public function authenticate()
    {
        // Custom authentication logic goes here!
    }
}

This is like Batman building his own Batsuit from scratch โ€“ you get to decide exactly how your custom authentication guard operates, so you can take down any bad guys that slip through the cracks! ๐Ÿฆธโ€โ™‚๏ธ๐Ÿ•ต๏ธโ€โ™€๏ธ

Alrighty then! Letโ€™s dive into the world of Laravel authentication, where superheroes arenโ€™t just in comics. When youโ€™ve got a legit user hanging around, ready to join the party, you can bestow upon them the keys to the kingdom with the Auth facadeโ€™s login method!

But first, let me tell you something important: that user needs to be a certified Authenticatable (itโ€™s like having a super-secret identity in this cyber world). You can find more details about it here, but for now just trust me, the App\Models\User model is already wearing that cape.

So, without further ado:

use Illuminate\Support\Facades\Auth;

// Time to give 'em the keys!
Auth::login($user);

Now, if your user fancies themselves as a modern-day Tony Stark and wants their session to last forever or until they personally deactivate it, you can pass a boolean value like so:

// Remember me? Yup! That's the one.
Auth::login($user, true);

Say youโ€™re dealing with a special group of users (like admins), and you want to assign them a specific set of powers:

// When in Rome, do as the Romans do... or in this case, admin!
Auth::guard('admin')->login($user);

And thatโ€™s your friendly guide on how to authenticate a user instance in Laravel! Now go forth and bring justice (or at least secure sessions) to your application. Happy coding! ๐Ÿค–๐Ÿš€

Alrighty then! Letโ€™s dive into the dance of digital authentication in Laravel Land. Buckle up, because itโ€™s going to be a wild ride!

Authenticate a User by Their Glorious ID Number

To verify that our cherished user is who they claim to be using their database recordโ€™s one-and-only unique identifier (a.k.a the primary key), you can employ the loginUsingId method. This trusty tool takes the number of the user you wish to authenticate as an argument:

Auth::loginUsingId(1); // Don't forget to replace "1" with your user's actual ID number!

Now, if you want to add a little extra spice to the mix by enabling the โ€œremember meโ€ feature for this lucky user, simply pass a boolean value as the remember argument of the loginUsingId method. If set to true, this means their session will be as tenacious as a pitbull with a bone โ€“ itโ€™ll stick around until they manually log out or you pry the keyboard from their cold, dead hands:

Auth::loginUsingId(1, remember: true); // Remember, the more you remember, the merrier!

Oh, and if youโ€™re wondering about authentications with a short shelf life, check out Authenticate a User Once for more information. Happy authenticating, partner! ๐Ÿค 

Alrighty then! Buckle up, because weโ€™re diving into the enchanting world of Laravel authentication where one dance with the login fairy is all it takes!

Dance with the Login Fairy Once ๐Ÿ’ƒ๐Ÿผ๐Ÿ•บ๐Ÿผ

In this whimsical land, you can charm a user into a magical dance with our trusty once method. This enchantment will ensure the user gets to tango with your application for just one request! No need for any session or cookie sorcery, and rest assured, no wedding bells will be ringing as the Login event remains blissfully unmarried.

if (Auth::once($credentials)) {
    // Now that we've danced, let's see what happens! ๐Ÿ•บ๏ธ
}

Just imagine, instead of a ballroom full of sessions and cookies, youโ€™re stepping into the spotlight with only one dance to prove your worth. Sounds like a fun challenge, doesnโ€™t it? Happy coding, adventurer! ๐Ÿค“โœจ

Space Age Secret Agent Authentication (AKA Basic Auth)

Welcome, secret agents of the Laravel universe! This chapter isnโ€™t about your tuxedos or martinis shaken, not stirred โ€“ itโ€™s about a slick way to authenticate your applicationโ€™s spies without setting up a fancy โ€œ007 loginโ€ hideout. Letโ€™s dive in!

HTTP Basic Authentication is our gadget of choice today. To kick things off, slap the auth.basic middleware onto a route. This mysterious contraption comes pre-packaged with the Laravel framework, so no need for secret formulas or blueprints!

Route::get('/profile', function () {
    // Only MI6-approved agents may access this mission...
})->middleware('auth.basic');

Once youโ€™ve secured your route with the middleware, hold onto your exploding pens โ€“ when you attempt to access the route in your browser, a popup will ask for your credentials! By default, our middleware believes that the email column in your users database table is your agentโ€™s โ€œagent number.โ€

Now, if you find yourself using FastCGI (we wouldnโ€™t want to leave out our friends in the field), there are a few extra steps involved. But donโ€™t worry โ€“ we have your back with an extensive troubleshooting guide in our user manual!

Remember, agents, security is crucial in our line of work. Keep those secrets safe and your mission successful!

Alright, hereโ€™s a humorous spin on the Laravel FastCGI documentation!

FastCGI Follies

If youโ€™re serving your Laravel application with a side of PHP FastCGI and a slice of Apache, you might find that HTTP Basic authentication is as confusing as a cat trying to use a computer. To set things right, try adding these lines to your applicationโ€™s .htaccess file:

RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Now, letโ€™s put on our detective hats and dive into the world of stateless HTTP Basic Authentication (okay, itโ€™s not that exciting, but stick with us!). When FastCGI is involved in your server setup, thereโ€™s a chance that the authorization headers get lost in translation, much like a secret recipe passed down through generations. By adding our magical lines above, we ensure that those crucial headers make it to their intended destination, saving your application from chaos and potential embarrassment!

Just remember, always keep an open bottle of code sanitizer handy when working with FastCGI โ€“ just in case things get a little too hairy!

Channeling the Spirit of Captain Authentication!

Ahoy there, matey! If youโ€™re tired of the usual session cookies and yearn for something a bit more pirate-y, weโ€™ve got just the thing - Stateless HTTP Basic Authentication! No need to walk the plank with all those session cookie shenanigans. Hoist the Jolly Roger of authentication directly to your applicationโ€™s API!

To set sail on this swashbuckling journey, youโ€™ll first need to concoct a middleware potion that summons the magical onceBasic method. If Blackbeard himself doesnโ€™t respond with a cryptic message, consider it fair game to continue your voyage through the application:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class AuthenticateOnceWithBasicAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Clossekin' Le Charmaine $next): Response
    {
        return Auth::onceBasic() ?: $next($request);
    }
}

Next, tie up the middleware to a route like a captain tying off his ship:

Route::get('/api/user', function () {
    // Only authenticated pirates may access this treasure chest...
})->middleware(AuthenticateOnceWithBasicAuth::class);

And if ye ever feel the need to log out, well, we canโ€™t help you there. This is the high seas, and once yeโ€™ve set sail with Basic Auth, itโ€™s a one-way ticket! But fear not, me hearty, for this will ensure only genuine pirates can access your treasure chest API! Yarr!

Lend Your Logout a Hand (or Two!)

Ready to give your users the olโ€™ heave-ho? Fear not, dear coder! Laravelโ€™s got a nifty logout method just for you, served up by the ever-helpful Auth facade. This little gem removes all that authentication data from their session, making subsequent requests as unauthorized as a kangaroo at a spelling bee.

But letโ€™s not stop there! You should also invalidate the userโ€™s session and whip up a fresh CSRF token like a seasoned pastry chef. Once thatโ€™s done, you can send your former user on their merry way back to the root of your application (because who doesnโ€™t love home sweet home after being kicked out?).

Hereโ€™s how you can pull this off:

Use the Force, young Padawan! I mean, use these lines of code...

use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;

/**
 * Send users packing from our application.
 */
public function logout(Request $request): RedirectResponse
{
    Auth::logout(); // Sayonara, authentication data! You're no longer needed here.

    $request->session()->invalidate(); // Let's make sure their session is as useless as a chocolate teapot!

    $request->session()->regenerateToken(); // And just for fun, let's give them a brand new CSRF token!

    return redirect('/'); // Off they go, back to the start... the root of all evil, or our application. You decide.
}

And if youโ€™re feeling particularly sneaky, donโ€™t forget to invalidate sessions on other devices as well! After all, nobody likes a user who hops from device to device like a digital kangaroo. ;)

Kickinโ€™ Sessions Off Other Gadgets (Without Being a Jerk to Your Current Buddy)

Laravel is like that cool friend who always has your back, even when you forget to lock the front door on Tinder date night. In this case, weโ€™re talking about a super-cool mechanism for kicking a userโ€™s sessions off other devices without leaving their current device high and dry (AKA still authenticated). This feature is perfect for those moments when a user updates their password and you want to ensure all other devices are logged out, while your current buddy stays safe in his cozy login zone.

First things first: Make sure the Illuminate\Session\Middleware\AuthenticateSession middleware is nestled amongst the routes that require session authentication. To do this, wrap it up like a burrito with other middleware on the route group definition so it can protect most of your appโ€™s routes. By default, you can apply it using the auth.session middleware alias:

Route::middleware(['auth', 'auth.session'])->group(function () {
    Route::get('/', function () {
        // ...
    });
});

Next, you can use the logoutOtherDevices method offered by the Auth facade. This method is like a bouncer at a club who only lets in folks with the right password: your app should accept this password through an input form.

use Illuminate\Support\Facades\Auth;

Auth::logoutOtherDevices($currentPassword);

When the logoutOtherDevices method is triggered, the userโ€™s other sessions will be given the boot (completely logged out), meaning they are now locked out of all guards they were previously authenticated by. Thatโ€™s one less device to worry about!

Alrighty then, letโ€™s dive into the password party scene in Laravel land! You know, where users get their password confirmation on, and weโ€™re here to make it as smooth as a catโ€™s tongue.

So, picture this: youโ€™ve got your application all jazzed up, and suddenly you realize that you need to add a password confirmation step before some sensitive actions or redirections to Fort Knox (aka the secure parts of your app). No worries, Laravel has got your back with a built-in middleware that will make this process as easy as baking a cake.

But wait! Before we get our bakerโ€™s hats on, you gotta define two routes: one route to serve up a view and ask the user for their password confirmation, and another route to verify that the entered password matches the original and then send them on their merry way to their final destination.

Note

This section of the docs will show you how to hook up with Laravelโ€™s password confirmation features directly. However, if you want to save some time (and who doesnโ€™t?), the Laravel application starter kits include support for this feature!

Now, letโ€™s get down to the nitty-gritty with password confirmation configuration! ๐Ÿš€๐Ÿš€๐Ÿš€

Ah, dear developer! Youโ€™ve stumbled upon the mystical realm where user authentication secrets are whispered and the password ghost haunts no more. Let me guide you through the enchanted forest of Laravel configuration, specifically thePassword Timeout Sanctum.

First off, once a user confirms their password in a fit of password-confirming passion, theyโ€™ll be left in sweet peace for three hoursโ€”no more pesky reminders to confirm again! But fear not, for you possess the power to alter this enchantment by tinkering with the value of password_timeout within your applicationโ€™s config/auth.php configuration file.

Adjusting this value is akin to spinning golden hairs in a magical wand. For instance, if you want to extend the password peace for 4 hours and 23 minutes (because who doesnโ€™t need an extra 23 minutes of bliss), simply update the password_timeout value accordingly!

Remember, with great power comes responsibilityโ€”so beware not to set it too low or you might find yourself fielding user complaints about the password ghost making a return appearance. Happy wandering in Laravelโ€™s enchanted forest, brave coder!

๐Ÿ›ฃ๏ธ The Magical Route Mapper ๐Ÿ›ฃ๏ธ

Navigating through your Laravel app is no walk in the park, but luckily weโ€™ve got a trusty Route Mapper to help us out! This powerful wizard will turn your URLs into actual working paths that lead you straight to your desired destinations. ๐Ÿง™โ€โ™‚๏ธ๐Ÿ”ฎ

๐Ÿ›Œ The Password Confirmation Form ๐Ÿ›Œ

Now, imagine youโ€™re at a wild party (in the before times), and you need to confirm that the mysterious stranger youโ€™ve been chatting up all night is indeed who they claim to be. Thatโ€™s where our password confirmation form comes in! Itโ€™s the perfect chance for them to prove their identityโ€ฆ or get left at the dance floor, we wonโ€™t judge. ๐Ÿ’ƒ๐Ÿ•บ

In Laravel, when users register, theyโ€™ll be prompted to create a password. But before they can really join the party (i.e., access your app), you want to make sure they confirm that password. Thatโ€™s where our trusty route comes in:

Route::get('/password/confirm/{id}/{hash}', 'Auth\ConfirmPasswordController@show')->name('password.confirm');

Hereโ€™s the lowdown on this magical route:

  1. /password/confirm/{id}/{hash} - The URL pattern. Replace {id} and {hash} with actual user data to create a unique URL for each user.
  2. Auth\ConfirmPasswordController@show - The controller that handles this route and displays the password confirmation form.
  3. name('password.confirm') - The name given to this route, which can be used later to link to it from other routes or views.

Now, you might be wondering how users will actually access this route. Fear not! Weโ€™ve got a nifty little mail function that sends out an email with the userโ€™s unique URL. Once they click on it, bam! Theyโ€™ll be directed straight to the password confirmation form. ๐Ÿ’Œ๐Ÿš€

Just remember: A successful party requires both food and drinks, so make sure your users can log in after confirming their passwords by linking them to a proper login route. Happy routing (and partying)! ๐ŸŽ‰๐Ÿฅณ

Alrighty, letโ€™s get this password party started! First off, we need to create a route that summons the password confirmation view, like a magic incantation for secure password validation.

Route::get('/secret_passphrase_verify', function () {
    return view('auth.password-confirmation-ceremony');
})->middleware('authenticate')->name('password.confirm');

Donโ€™t worry, thereโ€™s no need to call the secret serviceโ€”weโ€™ve got Laravel to handle this delicate matter! Just make sure your view has a form with a field called โ€œpasswordโ€, so we can compare passwords like long-lost twins. And sprinkle in some text for good measure, to let users know theyโ€™re about to enter the VIP lounge of your application and must prove their identity by reentering the secret handshakeโ€”er, password.

Now, before you embark on a wild goose chase for this view file (auth.password-confirmation-ceremony), remember that Laravel is like a caring concierge: it will create the missing view automatically when you call the make:auth command! So go ahead, channel your inner Indiana Jones and uncover the treasure (view file) with ease. ๐Ÿ†๐ŸŽ‰๐Ÿ™Œ

Alrighty then! Letโ€™s dive into some password fun times with our trusty Laravel pals. Weโ€™re about to set up a route for the โ€œConfirm Passwordโ€ form, which will be responsible for checking if that secret sauce you entered matches what weโ€™ve got on file. Hereโ€™s the lowdown:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

Route::post('/password-is-the-same-as-mine', function (Request $request) {
    if (! Hash::check($request->get('secretSauce'), $request->user()->password)) {
        return back()->withErrors([
            'secretSauce' => ['You're cooking with the wrong recipe, pal. Try again!']
        ]);
    }

    $request->session()->passwordVerified();

    return redirect()->intended('destination-of-your-dreams');
})->middleware(['auth', 'throttle:6,1']);

Now, letโ€™s break it down like the password confirmation process itself. First, Laravel checks if the magic password sauce you submitted actually matches our stored password for the authenticated user. If it does, we need to tell Laravelโ€™s session that the user has successfully proven their culinary prowess (I mean, password-matching skills). The passwordVerified method sets a timestamp in the userโ€™s session so Laravel knows when they last confirmed their password. And, voila! You get redirected to your intended destination like the master chef you are.

Remember, our route is now a well-guarded fortress, thanks to the mighty middleware array it carries: ['auth', 'throttle:6,1']. The 'auth' makes sure only authorized users can access this page, while 'throttle:6,1' ensures that they donโ€™t try to confirm their password more than once every 6 minutes. After all, even in the kitchen, we need to maintain some level of password security!

Password Party Checkpoint! ๐Ÿ•บ๏ธ

Before throwing a password dance party on your routes, make sure to assign the password.confirm bouncer! This groovy guard comes standard with every Laravel installation and works like a charm, stashing the userโ€™s desired destination in the session so they can boogie right back where they left off after confirming their new moves (password).

Hereโ€™s how you get this password party started:

Route::get('/settings', function () {
    // ...
})->middleware(['password.confirm']); ๐Ÿ’ƒ๏ธ๐ŸŽ‰

Route::post('/settings', function () {
    // ...
})->middleware(['password.confirm']); ๐Ÿ•บ๏ธ๐ŸŽŠ

After setting the stage for this password party, our bouncer will whisk users away to the password.confirm disco floor once theyโ€™ve proved their groove is up to par. Enjoy the fun times, folks! ๐Ÿ’ƒ๏ธ๐Ÿ•บ๏ธ๐ŸŽŠ๐ŸŽถ๐Ÿฅณ๐Ÿš€

Alrighty then! Letโ€™s dive into the world of custom authentication guards, shall we? You see, in Laravel land, you can create your own security squad using the extend method on the trusty Auth facade. But, like a secret recipe for grandmaโ€™s famous pie, this magic happens within a service provider. Since Laravel already sent over an AppServiceProvider, we can whip up our code right there!

<?php

namespace App\Providers;

use App\Services\Auth\JwtGuard;
// (Imagine an orchestra conductor waving a baton here)

class AppServiceProvider extends ServiceProvider
{
    // ...

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        // This is where the magic happens! (Cue: sparkly fairy dust)
        Auth::extend('jwt', function (Application $app, string $name, array $config) {
            // Return an instance of something that fits the bill...

            return new JwtGuard(Auth::createUserProvider($config['provider']));
        });
    }
}

As you mightโ€™ve noticed in the example above, the callback passed to the extend method should return an implementation of Illuminate\Contracts\Auth\Guard. This interface is like a blueprint for building a custom guard. Once your custom guard has been defined, you can reference it in the guards configuration of your auth.php configuration file:

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

Now, isnโ€™t that a piece of cake? Just remember, with great power comes great responsibility - make sure your custom guards secure Laravelโ€™s virtual frontier as if it were the real West! ๐Ÿค  ๐ŸŒต

Closure Comedy Guards (CCGs) - Laravelโ€™s Party Crasher for Authentication! ๐ŸŽ‰๐Ÿคนโ€โ™‚๏ธ

Want to throw a custom authentication bash in your application? Look no further than the Auth::viaRequest shindig! This method is like the life of the party, letting you define your dance moves (authentication process) using just one closure. ๐Ÿ•บ๏ธ๐ŸŽต

To kick things off, grab a mic and call the Auth::viaRequest at the boot party of your applicationโ€™s AppServiceProvider. The viaRequest function will happily accept an authentication driver name as its first drink (yup, itโ€™s that kind of party). Pick something cool and catchy for your custom guard. And for the main act, pass a closure that takes the incoming HTTP request, does a quick spin around the dance floor (queries your user model), then returns either a user instance or, if things go south, sends everyone home with a big olโ€™ null ๐Ÿคทโ€โ™‚๏ธ๐Ÿ™…โ€โ™€๏ธ:

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

/**
 * Get the party started!
 */
public function boot(): void
{
    Auth::viaRequest('custom-token', function (Request $request) {
        return User::where('token', (string) $request->token)->first(); // Party on, Garth and Wayne!
    });
}

Once your custom authentication driver is all dolled up, itโ€™s time to invite it to the big dance by configuring it as a driver within the guards configuration of your auth.php configuration file:

'guards' => [
    'api' => [
        'driver' => 'custom-token',
    ],
],

Now, you can reference your guard when assigning the authentication middleware to a route (think of it as the bouncer checking IDs):

Route::middleware('auth:api')->group(function () {
    // ...
});

And thatโ€™s a wrap! Now you can show off your custom CCG moves and keep unwanted guests at bay ๐Ÿ•บ๏ธ๐Ÿ’ƒ!

Alright, Laravel buddies! Letโ€™s dive into the realm of custom user providers because, letโ€™s face it, who needs a traditional relational database when you can store your users in a cosmic crystalline cluster or a sentient network of refrigerators? ๐ŸŒŒ๐Ÿ”

First off, extend Laravel with your own authentication user provider like youโ€™re inviting the coolest kid in school to your party. Weโ€™ll do this by calling the provider method on the ever-so-charming Auth facade. The user provider resolver should return an implementation of Illuminate\Contracts\Auth\UserProvider, which, if youโ€™re not a fan of long names, can be shortened to ICAAUP for fun ๐Ÿ˜‰

Hereโ€™s the party invite in PHP:

<?php

namespace App\Providers;

use App\Extensions\MongoUserProvider;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    // ...

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Auth::provider('mongo', function (Application $app, array $config) {
            // Return an instance of ICAAUP...

            return new MongoUserProvider($app->make('mongo.connection'));
        });
    }
}

Once youโ€™ve sent the invite, itโ€™s time to let your new provider join the dance floor in your auth.php configuration file. First, define a provider that uses your new driver:

'providers' => [
    'users' => [
        'driver' => 'mongo',
    ],
],

Finally, you can reference this provider in your guards configuration. Itโ€™s like adding them to the guest list:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
],

And there you have it! Now, your custom user provider is welcome at the Laravel party ๐ŸŽ‰ Just remember, with great power comes great responsibility (and a cool new dance move)!

The User Provider Contract: The Unsung Heroes of Authentication!

These unsung heroes, Illuminate\Contracts\Auth\UserProvider implementations, are like the trusty sidekicks that ensure our Laravel heroes can continue their quest for justice, even when user data storage systems get a little messy or the villain decides to switch databases (gasp!).

Letโ€™s dive into the Illuminate\Contracts\Auth\UserProvider contract:

<?php

namespace Illuminate\Contracts\Auth;

interface UserProvider
{
    public function retrieveById($identifier);
    public function retrieveByToken($identifier, $token);
    // And so on... (rest of the methods)
}

The retrieveById function is like a super-powered librarian, locating a user based on their unique library card number (or auto-incrementing ID if weโ€™re sticking with the database metaphor). Once found, this scholarly sidekick returns the corresponding Authenticatable implementation.

The retrieveByToken function is our secret service agent, finding users by their โ€œremember meโ€ token and unique identifier, often stored in a hidden column like remember_token. This secret squirrel then returns the matching Authenticatable implementation.

The updateRememberToken method acts as the helpful office assistant, updating the userโ€™s remember_token with a fresh token for successful โ€œremember meโ€ authentication attempts or when users decide to log off (and hopefully remember their passwords next time).

The retrieveByCredentials function is our undercover detective, investigating the array of credentials passed to the Auth::attempt method when attempting to authenticate. This snoopy sidekick then searches for the matching Authenticatable implementation in the underlying persistent storage system. But remember, this method should never engage in password validation or authentication itself!

The validateCredentials method is our courtroom prosecutor, cross-examining the given user with the provided credentials to authenticate the user. This prosecuting attorney will often use the Hash::check method to compare the value of $user->getAuthPassword() with the value of $credentials['password']. If successful, this method returns a resounding โ€œGUILTY!โ€ (or true), while an unsuccessful attempt results in โ€œNOT GUILTYโ€ (or false).

Finally, the rehashPasswordIfRequired function acts as our trusty IT technician, rehashing the given userโ€™s password if necessary and supported. This tech-savvy sidekick uses the Hash::needsRehash method to determine whether the $credentials['password'] needs to be updated, and if so, employs the Hash::make method to perform the password rehashing magic and update the userโ€™s record in the underlying persistent storage system.

Alrighty then! Letโ€™s dive into the heart of the action โ€“ the Authenticatable contract. After exploring the dance moves of the UserProvider, itโ€™s time to learn the twirls and pirouettes of this beauty.

Remember, user providers should return objects that can do the Macarena to this interface from the retrieveById, retrieveByToken, and retrieveByCredentials methods:

<?php

namespace Illuminate\Contracts\Auth;

interface Authenticatable
{
    public function getPrimaryDancerName(); // "What's my name? Call me Mr. PK!"
    public function getPrimaryDancerId();   // The dancer with the golden moves!
    public function getPasswordColumnName(); // Where the secret sauce is kept: Passwordville, Population: 1
    public function getHashedSecretSauce(); // The password, after it's been put through the magic blender

    public function getRememberTokenName();   // What's my dance ticket number? Call me Mr. RT!
    public function setRememberToken($value);  // Stamping my dance ticket for a comeback performance!
}

This interface is as simple as a one-legged flamenco dancer โ€“ the getPrimaryDancerName method tells us the name of the โ€œprimary keyโ€ column for our dance partner, while the getPrimaryDancerId method brings center stage the โ€œprimary keyโ€ of our beloved dancer. When using a MySQL back-end, this would likely be the auto-incrementing primary key assigned to our dance record. The getPasswordColumnName method reveals the name of the password column in the dance studio, while the getHashedSecretSauce method serves up the dancerโ€™s shimmy-shaken password.

This interface allows the dance floor to accommodate any โ€œuserโ€ class, regardless of what dance troupe or stage decor you are using. By default, Laravel includes an App\Models\User class in the app/Models directory which can do all the fancy footwork!

Now, for the grand finale โ€“ automatic password rehashing! This nifty feature makes sure that when a user updates their password, it gets hashed using the latest algorithm. No more worry about your moves being outdated! The Illuminate\Hashing\Hasher class handles all the hash-tastic responsibilities for you. Just call the make() method to get an instance of this class, and then use the hash() method to hash a password.

For example:

use Illuminate\Hashing\Hasher;

$hasher = new Hasher();
$hashedPassword = $hasher->make('secret sauce'); // Shimmy-shaken and ready for the dance floor!

And there you have it โ€“ a humorous yet informative overview of the Authenticatable contract! Now, letโ€™s get this party started! ๐ŸŽ‰๐Ÿ’ƒ๐Ÿ•บ๏ธ

Alright, buckle up, password peeps! ๐Ÿšจ Laravelโ€™s default password encryption system is none other than the illustrious bcrypt. Think of it as a digital bouncer for your userโ€™s secret sauce (passwords), ensuring only the right passwords get through the door.

The โ€œwork factorโ€ for these digital doormen can be adjusted, like fine-tuning a vintage vinyl record player, using your applicationโ€™s config/hashing.php configuration file or the BCRYPT_ROUNDS environment variable. As CPUs and GPUs get stronger, just like weightlifters at the gym, youโ€™ll want to bump up the work factor for bcrypt to keep those passwords nice and secure.

When you do decide to beef up your bcrypt muscle, Laravel will treat your users with an elegant dance of rehashing - automatically and effortlessly! This magic happens when your users authenticate via Laravelโ€™s starter kits or when you manually authenticate them using the attempt method. Itโ€™s like having a digital butler who keeps all passwords up-to-date without causing a fuss.

However, if you find this automatic rehashing disruptive to your applicationโ€™s rhythm (we wouldnโ€™t blame you), you can disable this feature by publishing the hashing configuration file:

php artisan config:publish hashing

Once thatโ€™s done, simply set the rehash_on_login configuration value to false:

'rehash_on_login' => false,

Remember, this only affects automatic rehashing during user authentication. Your users will still be eternally grateful for your commitment to keeping their passwords secure! ๐Ÿ”๐Ÿ’ช๐Ÿผ

Alright, Laravelโ€™s not just a party animal, but it sure knows how to throw a heck of an authentication bash! Hereโ€™s the lineup of events you can tap into and make your own:

  1. Illuminate\Auth\Events\Registered - The fresh-faced newcomer stumbling through the door, eager to mingle and get their dance card punched (a.k.a., registered)!
  2. Illuminate\Auth\Events\Attempting - The wallflower making their way to the dance floor, nervously trying to find a partner (attempting to log in).
  3. Illuminate\Auth\Events\Authenticated - The successful match made at last call (authenticated)! Congratulations, you two lovebirds!
  4. Illuminate\Auth\Events\Login - The grand entrance of our newly crowned king and queen of the dance floor (logging in).
  5. Illuminate\Auth\Events\Failed - Sorry buddy, looks like your moves just didnโ€™t quite cut it tonight (failed to log in).
  6. Illuminate\Auth\Events\Validated - The security guard checking IDs at the door, making sure everyone is who they say they are (verifying identities).
  7. Illuminate\Auth\Events\Verified - The VIP guest list coordinator verifying their RSVPs and giving the green light (verifying emails).
  8. Illuminate\Auth\Events\Logout - One too many drinks, time to call it a night and head home (logging out).
  9. Illuminate\Auth\Events\CurrentDeviceLogout - A quick goodbye at the exit, leaving behind some memories (logout from current device).
  10. Illuminate\Auth\Events\OtherDeviceLogout - The unexpected booty call text at 3 AM, confirming your worst fears (someone else logged out from another device).
  11. Illuminate\Auth\Events\Lockout - Security getting a little too tight for comfort (locked out after too many failed attempts).
  12. Illuminate\Auth\Events\PasswordReset - The wake-up call the morning after, when you canโ€™t quite remember what happened last night (password reset).
  13. Illuminate\Auth\Events\PasswordResetLinkSent - The text message from a concerned friend offering help (password reset link sent).

Our network