Laravel

How to set up dynamic email templates with Laravel and ensure fallbacks?

December 3, 2025

download ready
Thank You
Your submission has been received.
We will be in touch and contact you soon!

Use database-stored templates with spatie/laravel-database-mail-templates for dynamic content via placeholders {{ $user->name }}, fallback to Blade files if DB template missing, and pass data arrays for full customization.

Store HTML templates in DB with unique slugs, replace variables using str_replace() or Blade rendering, and chain ->fallback('emails.default') to use static Blade if dynamic fails. Supports admin editing, A/B testing, and personalization without code changes.

Code

composer require spatie/laravel-database-mail-templates
php artisan vendor:publish --provider="Spatie\MailTemplates\MailTemplatesServiceProvider"
php artisan migrate
  • Mailable with fallback:-

Code

class UserWelcomeMail extends Mailable {
    public $data;
    
    public function __construct($data) {
        $this->data = $data;
    }
    
    public function envelope() {
        return new Envelope(
            subject: 'Welcome!',
            using: 'welcome' // DB template slug
        );
    }
    
    public function content() {
        return new DatabaseView(['data' => $this->data]); // With fallback
    }
}
  • Send with data

Code

Mail::to($user)->send(new UserWelcomeMail([
    'name' => $user->name,
    'url' => route('verify', $user)
]));
// Template in DB: <h1>Hi {{ $data['name'] }}!</h1>
Hire Now!

Need Help with Laravel Development ?

Work with our skilled laravel developers to accelerate your project and boost its performance.
**Hire now**Hire Now**Hire Now**Hire now**Hire now