Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Mailables in Laravel

Introduction

Mailables in Laravel provide a convenient way to send emails through your application. They allow you to create reusable email templates and encapsulate the logic for sending emails. This tutorial will guide you through the process of creating and using Mailables in Laravel.

Prerequisites

Before we begin, ensure you have the following:

  • Laravel installed on your local development environment.
  • An SMTP server or email service provider (like Mailgun, SendGrid, etc.) configured in your Laravel application.

Creating a Mailable

You can create a Mailable using the Artisan command. Open your terminal and run the following command:

php artisan make:mail OrderShipped

This command will create a new Mailable class in the app/Mail directory. You can customize this class to include the content and data needed for your email.

Defining the Mailable Class

Open the newly created Mailable class located at app/Mail/OrderShipped.php. Here’s an example of what it might look like:

class OrderShipped extends Mailable
{
    public $order;

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

    public function build()
    {
        return $this->view('emails.orders.shipped')
                    ->with(['order' => $this->order]);
    }
}
                

In this example, we define a public property $order that holds the order data. The constructor accepts an $order parameter, which we assign to the property. The build method specifies the view to be used for the email and passes the order data to it.

Creating the Email View

Next, you need to create the email view that will be used to render the email. Create a new Blade file at resources/views/emails/orders/shipped.blade.php and add the following content:




    Order Shipped


    

Your Order Has Shipped!

Thank you for your order. Your order number is: {{ $order->id }}