0
0
Laravelframework~5 mins

Mail templates in Laravel

Choose your learning style9 modes available
Introduction

Mail templates help you send emails with a nice, consistent look. They save time by reusing the same design for many emails.

When sending welcome emails to new users.
When notifying users about password resets.
When sending order confirmations in an online store.
When sending newsletters or updates to subscribers.
When you want all your emails to have the same style and branding.
Syntax
Laravel
php artisan make:mail YourMailName --markdown=emails.template_name

// In the generated mail class:
public function build()
{
    return $this->markdown('emails.template_name')
                ->with(['data' => $this->data]);
}

Use --markdown to create a mail template using Markdown syntax.

The markdown() method points to the Blade template for the email.

Examples
This command creates a mail class named WelcomeUser with a Markdown template at resources/views/emails/welcome.blade.php.
Laravel
php artisan make:mail WelcomeUser --markdown=emails.welcome
This method tells Laravel to use the emails.welcome template and pass the user data to it.
Laravel
public function build()
{
    return $this->markdown('emails.welcome')
                ->with(['user' => $this->user]);
}
This is a simple Markdown mail template. The subject sets the email subject, and the body uses Blade syntax to show the user's name.
Laravel
---
subject: "Welcome to Our Site"
---

# Hello, {{ $user->name }}!

Thanks for joining us.
Sample Program

This example shows a mail class WelcomeUser that sends a welcome email using a Markdown template. The template greets the user by name. The mail is sent to the user's email address.

Laravel
<?php

namespace App\Mail;

use Illuminate\Mail\Mailable;

class WelcomeUser extends Mailable
{
    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    public function build()
    {
        return $this->markdown('emails.welcome')
                    ->with(['user' => $this->user]);
    }
}

// resources/views/emails/welcome.blade.php
---
subject: "Welcome to Our Site"
---

# Hello, {{ $user->name }}!

Thanks for joining us.

// Usage example in a controller or route:
use App\Mail\WelcomeUser;
use Illuminate\Support\Facades\Mail;

$user = (object) ['name' => 'Alice'];
Mail::to('alice@example.com')->send(new WelcomeUser($user));
OutputSuccess
Important Notes

Mail templates use Blade and Markdown for easy formatting.

You can customize the email subject in the template front matter.

Always test emails locally using tools like MailHog or Mailtrap before sending to real users.

Summary

Mail templates let you create reusable email designs.

Use php artisan make:mail with --markdown to create templates.

Pass data to templates using the with() method in the mail class.