The Incredible Journey of Email Verification! ๐Ÿš€๐Ÿ“ง

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

Browse funny laravel docs
On this page

Get ready to embark on an epic adventure through the magical land of account verification! ๐ŸŽ‰๐ŸŒˆ

Prepping Your Model (Our Brave Knight) ๐Ÿ›ก๏ธ

Before setting off, make sure your model is well-equipped with all the necessary email verification traits. Donโ€™t forget to arm it with a verified_email field! โš”๏ธ๐Ÿ“

Setting Up the Kingdom (Database) ๐Ÿฐ๐Ÿ—บ๏ธ

Now that your model is prepared, letโ€™s lay out our kingdomโ€™s infrastructure. Create a verified_emails table and all its glorious columns to keep track of our verification statuses! ๐Ÿ‘‘๐Ÿ—๏ธ

The Royal Route (Routing) ๐Ÿšฆ๐Ÿฐ

Navigate through the winding roads of routing, where weโ€™ll establish several essential stops along the way.

The Verification Notice Post Office ๐Ÿ“ฃ๐Ÿ—ž๏ธ

Our first stop is at the post office, where weโ€™ll compose and send out the initial verification emails to our subjects! ๐Ÿ’Œ๐Ÿ”ฅ

The Verification Handler (The Royal Court) ๐Ÿฐโœ๏ธ

Next, letโ€™s head over to the royal court, where our brave knights will handle the verification requests received from all corners of the land. ๐Ÿ›ก๏ธ๐Ÿ‘‘

Resending the Misplaced Letter (Email) ๐Ÿ“ง๐Ÿ”

In case a letter gets lost in transit, weโ€™ll need to implement a system for resending those emails with a friendly reminder! ๐Ÿ“ฎ๐Ÿ˜ฑ

Protecting Our Castle from Intruders (Protecting Routes) ๐Ÿ›ก๏ธ๐Ÿฏ

Lastly, letโ€™s fortify our castle walls by ensuring that only verified subjects can enter the realm of protected routes! ๐Ÿฐ๐Ÿ”

Customizing Our Kingdom (Customization) ๐ŸŽจ๐Ÿ‘‘

Once weโ€™ve established the foundations, letโ€™s make our kingdom truly unique by customizing every little detail to our liking! ๐ŸŽจ๐Ÿ’…

Announcing Royal Happenings (Events) ๐Ÿ“ข๐Ÿฐ

Last but not least, letโ€™s celebrate the joyous moments of email verification with events, complete with fanfare and fireworks! ๐ŸŽ‰๐ŸŽ‡

Letโ€™s Get Verified, Shall We?

Attention all web adventurers! If youโ€™ve ever found yourself in a pickle trying to wrangle your usersโ€™ emails like a digital wrasslinโ€™ match, fear no more! Laravel, your friendly neighborhood super-library, is here to save the day with its email verification services. No need for repetitive strain injury when building each new app - weโ€™ve got your back!

[!ATTN: BAMF ALERT] Ready to sprint past the competition? Get your cape flying with one of our Laravel application starter kits in a fresh Laravel app. These kits will whisk you off your feet, scaffolding an entire authentication system (including email verification, because weโ€™re all about making life easier).

Now, letโ€™s get our models ready for the big event! (No tuxedos required.)

Alright, letโ€™s dive into the world of Laravel Model Prep-show! ๐ŸŽฏ Before we get our groove on, make sure your App\Models\User model is not shy and knows how to dance with the Illuminate\Contracts\Auth\MustVerifyEmail contract. Hereโ€™s a little jive it might want to learn:

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;  // Don't be a wallflower, join the dance floor!
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    // ...
}

Once itโ€™s learned this dance, newly registered users will receive an email invitation to join the partyโ€”an email containing a verification link. The best part? Laravel is the ultimate hype man, automatically registering the Illuminate\Auth\Listeners\SendEmailVerificationNotification listener for the Illuminate\Auth\Events\Registered event, ensuring your model gets all the attention it deserves! ๐ŸŽ‰

If your application is more of a DIY project and youโ€™re manually implementing registration instead of using one of our starter kits, donโ€™t forget to dispatch the Illuminate\Auth\Events\Registered event after a userโ€™s successful registration:

use Illuminate\Auth\Events\Registered;

event(new Registered($user));  // Send out those invitations!

Now, letโ€™s get this party started! ๐Ÿฅณ

Alrighty, letโ€™s get our nerd on and dive into the world of Laravel Database Preparation!

First things first, itโ€™s time to deck out your users table with some swanky new digs. This is where we add an email_verified_at columnโ€”a chic little place to store the exact moment that one of your users officially verified their email address. You can think of this as the โ€œred carpetโ€ or the โ€œofficial welcome-to-the-partyโ€ of the digital world for your user.

Now, you might be wondering where this magical column comes fromโ€”worry not! Laravelโ€™s default 0001_01_00_000001_create_users_table.php database migration is where it hangs out when itโ€™s not making new friends in your database.

But wait, thereโ€™s more! The party doesnโ€™t stop hereโ€”weโ€™ve just stepped into the cocktail hour of our Laravel journey. Next up, weโ€™ll learn about routing for email verification! (Cue confetti and champagne bottles popping open) ๐ŸŽ‰๐Ÿฅณ๐Ÿพ

Just kidding, itโ€™s not really that fancyโ€”but it is pretty darn important. Letโ€™s get this show on the road!

Ahoy there, intrepid Laravel coders! ๐ŸŒด๐Ÿ  Letโ€™s dive into the vibrant world of routing, shall we? ๐ŸŒŠ๐Ÿคฟ

First off, we need to create a route that serves as a friendly reminder to our users. You know, like when your mom tells you to put on a jacket before heading outside. In this case, itโ€™s telling them to click the email verification link that Laravel sent them after they registered - itโ€™s their gateway to becoming a fully-fledged member of our awesome community! ๐ŸŽ‰๐ŸŽŠ

Next up, weโ€™ve got the route that will handle requests like a well-trained butler handling a high tea service. You know, graceful, efficient, and just a little bit snobby. This route is in charge when our users click the verification link in their email. Itโ€™ll take care of verifying their account, allowing them to join the ranks of the verified and respected! ๐ŸŒ๐Ÿ‘‘

Last but certainly not least, we need a route that will come to the rescue when users accidentally lose the first verification link. Itโ€™s like finding your car keys in the fridge - sometimes things just get misplaced, and youโ€™ve got to have a backup plan! This route will send a new verification link to help our users get back on track. ๐Ÿ”‘โ˜•๏ธ

So there you have it, three routes that will guide our users through the email verification process like a well-choreographed dance. Now go forth and route with pride, dear developers! ๐Ÿ’ƒ๐Ÿ•บ๐ŸŒ๐Ÿ’ช

Alrighty then! Letโ€™s get our virtual feathers all ruffled about email verification, shall we? ๐Ÿฆƒ

As weโ€™ve chirped before, itโ€™s pivotal to establish a route thatโ€™ll serve up a view asking your newly-registered user to peck on that email verification link they got from Laravel post-registration. This view is quite the peacock strut when users attempt to flutter about other parts of your app sans verified email address. Remember, this link will automatically be sent out like a digital carrier pigeon as long as your App\Models\User model dons the snazzy MustVerifyEmail interface:

Route::get('/email/verify', function () {
    return view('auth.verify-email');
})->middleware('auth')->name('verification.notice');

Now, mark this route down in your rolodex as verification.notice. Itโ€™s crucial that this name ainโ€™t altered a bit since the verified middleware (which comes bundled with Laravel) will perform a clever little redirect to this route name if a user hasnโ€™t verified their email address yet.

Note

When crafting your email verification process by hand, youโ€™ll be expected to compose the contents of that very same verification notice view yourself. If you fancy some assistance with all things authentication and verification views, take a gander at our Laravel application starter kits.

Now, wasnโ€™t that a bit more enjoyable? ๐Ÿ˜Ž Letโ€™s keep the web development party going!

Alrighty then! Letโ€™s dive into the world of email verification in Laravel land. First off, we need to create a route thatโ€™ll handle those clicky-clicky moments when users confirm their emails by following the link we send โ€˜em. This magical route should be christened verification.verify and decked out with the auth and signed middlewares, much like a fancy ball gown at a regal soiree. Hereโ€™s the code to make it all happen:

use Illuminate\Foundation\Auth\EmailVerificationRequest;

Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
    $request->fulfill();

    return redirect('/home');
})->middleware(['auth', 'signed'])->name('verification.verify');

Now, take a gander at this route. Youโ€™ll notice weโ€™re using an EmailVerificationRequest instead of the usual Illuminate\Http\Request โ€“ think of it like wearing a cape instead of a plain t-shirt to feel extra superhero-ish. The EmailVerificationRequest is a fancy form request that comes with Laravel, making it an automatic validator for the id and hash parameters in our request.

Next up, we call the fulfill method on the request, which is like pressing the big olโ€™ โ€œVerify Emailโ€ button in your email client (but more technical). This method takes care of marking the userโ€™s email as verified and dispatches an Illuminate\Auth\Events\Verified event โ€“ perfect for all your celebratory email-verification needs. The markEmailAsVerified method is available to the default App\Models\User model via the Illuminate\Foundation\Auth\User base class. Once the userโ€™s email address has been verified, you can send โ€˜em off to any olโ€™ destination you fancy.

Now, letโ€™s say our users are a bit forgetful and need another chance at verifying their emails. We can create a helper function for sending the verification email again:

use Illuminate\Support\Facades\URL;

function sendVerificationEmail($user) {
    $verificationUrl = URL::temporarySignedRoute(
        'verification.verify', now()->addMinutes(60), [
            'id' => $user->getEmailForVerification(),
            'hash' => sha1($user->getEmailForVerification()),
        ]
    );

    // ... Send the email here with the verification url
}

This function generates a new verification URL for the user, which they can click to verify their email. The URL is time-limited and secure, thanks to being signed and hashed. Youโ€™ll want to plug this function into your registration or forgotten password process โ€“ just make sure to send the user on an exciting email journey!

Re-sending the Lost-in-Space Verification Email

Whoopsy daisies! Ever found yourself in a pickle when your userโ€™s verification email went rogue on its intergalactic journey? Fear not, dear coder friend, for we have a cosmic solution to this celestial conundrum. To help our space-lost users hail their verification emails back home, you can set up a stargate (route) for them to request a reboot:

Use your phaser on 'stun' and import Illuminate\Http\Request;

Route::post('/alien_emails/recall', function (Request $request) {
    $request->user()->sendAlienEmailVerificationNotification();

    return back()->with('message', 'Verification beacon activated!');
})->middleware(['auth', 'throttle:6,1'])->name('verification.beacon');

Now, just hide this โ€œrequest re-sendโ€ button in your extra-terrestrial verification notice view to keep the surprise until itโ€™s needed for an emergency interstellar rescue mission.

Securing Your Routes Like a Fort Knox for Pigeons!

Ah, the sweet sound of digital security! Welcome to Laravelโ€™s Route Middleware, where we protect our routes from unverified users - think of it as a bouncer at the hottest club in town.

But instead of a velvet rope, we use something called a verified middleware alias, which is just a fancy way of saying โ€œThatโ€™s right, pal! Show us your verification email!โ€ The best part? Laravel has already registered this bouncer for you, so all you need to do is slap on the wristbands (attach the middleware).

Hereโ€™s how you do it:

Route::get('/profile', function () {
    // Only verified users with a valid membership bracelet may enter...
})->middleware(['auth', 'verified']);

Now, if an unverified user tries to crash the party (access a route), theyโ€™ll be politely escorted to the verification.notice route - think of it as the line outside the club, waiting for their verification email.

And hey, you can even customize this bouncer! If you want to change the music or the drink prices, wellโ€ฆ Laravelโ€™s got your back with named routes. Just remember, itโ€™s all about keeping the club (your application) secure and the tunes bumpinโ€™! ๐Ÿฅณ๐Ÿš€๐ŸŽ‰

Ahoy there, code swashbucklers! If youโ€™re feeling a tad adventurous and want to personalize your Laravel ship, this section is right up your alley. Letโ€™s dive in, shall we? ๐ŸŒŠ๐Ÿฌ

Verification Email Customization

Ah, the thrill of sending out a beautifully crafted verification email that makes the recipient say โ€œWow, this Laravel pirate really knows how to code!โ€ Letโ€™s hoist the mainmast and set sail on customizing your verification emails. ๐Ÿดโ€โ˜ ๏ธ

  1. Create a new view: You can create a new blade file in the emails directory, giving it the name of the email you want to customize (e.g., verify for the welcome email).
php artisan make:mail verify
  1. Edit the newly created file: Now that you have your very own verification email template, feel free to tinker with it to your heartโ€™s content. Donโ€™t forget to use Laravelโ€™s built-in helper functions like trans($key) and url($url).

  2. Set the view for the welcome email: Open up your AppServiceProvider class and letโ€™s point the welcome email towards its newly customized destination by updating the sendVerificationEmail method:

use Illuminate\Support\Facades\Mail;

// ...
public function boot()
{
    $this->app->booted(function () {
        if ($this->app->environment('local', 'testing')) {
            event(new \Illuminate\Queue\Events\Queued($this->app['queue']));
        }

        Mail::send(['html' => 'emails.verify'], $data, function ($message) {
            // Customize your email here! ๐ŸŽจ
        });
    });
}

Now, the next time a user signs up for your Laravel treasure hunt, theyโ€™ll be greeted with an email that is nothing short of a masterpiece. ๐ŸŽ‰

Remember, customization is like adding a parrot on your shoulder โ€“ it makes you stand out from the rest! So, grab your compass and set sail towards even greater adventures in Laravel land. Arr matey! ROT ๐Ÿดโ€โ˜ ๏ธ

Ahoy there, code pirates! ๐ŸŒด๐ŸŒŠ If youโ€™re here, it means youโ€™ve taken the plunge into Laravel waters and are ready to customize that email verification shanty of yours. ๐ŸŽบ๐Ÿ“ง

By default, our shipshape emails should be enough to make Davy Jones himself click โ€˜verifyโ€™, but if ye hanker for more, Laravel lets you refit the cannons (email notifications) to your heartโ€™s desire! ๐Ÿณ๐ŸŒฎ

To embark on this customization voyage, hoist the sail and pass a โ€˜closureโ€™ matey, to the toMailUsing method, provided by the Illuminate\Auth\Notifications\VerifyEmail notification. This closure will accept two arguments: the notifiable model instance thatโ€™s about to get its inbox flooded, and the signed email verification URL the user must navigate to verify their email address. The closure should eventually return an instance of Illuminate\Notifications\Messages\MailMessage.

Youโ€™ll want to set sail from the boot method of your applicationโ€™s AppServiceProvider class:

use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Notifications\Messages\MailMessage;

/**
 * Shake the ship's rigging and wake up the crew.
 */
public function boot(): void
{
    // ...

    VerifyEmail::toMailUsing(function (object $notifiable, string $url) {
        return (new MailMessage)
            ->subject('Yo Ho, Verify Yonder Email Address')
            ->line('Arrr, click this button below to verify yer email address.')
            ->action('Verify Email Address', $url);
    });
}

Note

If ye want more tales of the sea (mail notifications), hoist the Jolly Roger and head over to the mail notification documentation. ๐Ÿดโ€โ˜ ๏ธโš“๏ธ

Alright, listen up, tech-savvy cowpokes! Letโ€™s gallop into the wild world of Laravel Events, shall we?

When youโ€™re corralling those app ponies with our handy starter kits (available at /docs/{{version}}/starter-kits), Laravel saddles up and fires off an Illuminate\Auth\Events\Verified event during the email verification rodeo. Now, if youโ€™re handling your own wrangling of emails for your application, you might find yourself hankering to manually unleash these events after the lassoing is done.

So, put on your ten-gallon hat and letโ€™s get this roundup started! If youโ€™re itchinโ€™ to learn more about Laravel Events, you can head over to /docs/{{version}}/events for some educational horseback riding. Yeehaw! ๐Ÿค ๐ŸŽ๐ŸŒต

Our network