Laravel provides a powerful and convenient way to send Email notifications in Laravel via various channels, including email. This is particularly useful for alerting users about events, updates, or any other important information. In this article, we’ll walk through the basics of sending email notifications in Laravel with a simple example.
Setting Up Email Notifications in Laravel
1. Configure Mail Settings
Before sending emails, you need to configure your mail settings. Open your .env file and set up your mail configuration:
Example:
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your_email@example.com
MAIL_FROM_NAME=”${APP_NAME}”
Replace the values with your actual mail server credentials. If you’re using a service like Mailtrap for testing, provide those credentials.
2. Create a Notification
Laravel’s artisan command makes it easy to generate a notification. Run the following command in your terminal:
php artisan make:notification OrderShipped
This command creates a new notification class in the app/Notifications directory.
3. Define the Notification
A many-to-many relationship is used to define records in one table that are associated with multiple records in another table and vice versa.
Example:
<?php namespace App\Notifications; use Illuminate\Notifications\Notification; use Illuminate\Notifications\Messages\MailMessage; class OrderShipped extends Notification{ protected $order; public function __construct($order){ $this->order = $order; } public function via($notifiable) { return ['mail']; } public function toMail($notifiable){ return (new MailMessage) ->subject('Your Order Has Been Shipped!') ->greeting('Hello!') ->line('We are happy to inform you that your order has been shipped.') ->line('Order ID: ' . $this->order->id) ->action('Track Order', url('/orders/' . $this->order->id)) ->line('Thank you for shopping with us!'); } }
In this example, the OrderShipped notification sends an email when an order is shipped, including details like the order ID and a link to track the order.
4. Send the Notification
To send the notification, use the notify method on any Notifiable entity, such as a User. For example, you might send the OrderShipped notification when an order is marked as shipped:
Example:
<?php use App\Notifications\OrderShipped; use App\Models\User; // Assuming $user is the user who placed the order $user->notify(new OrderShipped($order));
5. Customize the Notification
You can further customize your notifications by adding more channels (like SMS, database, etc.) or by modifying the email template. Laravel also allows you to create custom mail templates if you want more control over the design.