Laravel provides a simple and flexible notification system that supports channels like email, database, SMS, and Slack. You can create notifications using the artisan make:notification
command and send them using the notify()
method. Each notification can define how it should be delivered using the via()
method. You can customize the content using methods like toMail()
or toDatabase()
. Notifications help keep users informed through various channels from a single codebase.
Step 1: Set Up Mail in .env
(for email notifications)
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your_email_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your_email@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
For Gmail: Enable App Passwords if 2FA is enabled.
Step 2: Create a Notification
Put this comment in your project terminal:
php artisan make:notification WelcomeNotification
Step 3: Edit Notification Logic
Open: app/Notifications/WelcomeNotification.php
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
class WelcomeNotification extends Notification
{
public function via($notifiable)
{
return ['mail']; // you can add 'database', 'sms', etc.
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Welcome to Laravel!')
->line('Thank you for joining our platform.')
->action('Visit Site', url('/'))
->line('We’re glad to have you!');
}
}
Step 4: Enable Notifications on User Model
In app/Models/User.php
:
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
}
Step 5: Send Notification from Controller
app/Http/Controllers/NotificationController.php
use App\Models\User;
use App\Notifications\WelcomeNotification;
public function notifyUser()
{
$user = User::find(1); // or any user
$user->notify(new WelcomeNotification());
return "Notification Sent!";
}
Summary
Step | Command/Code |
---|---|
Create notification | php artisan make:notification |
Enable on model | Use Notifiable trait |
Send notification | $user->notify(new MyNotification) |
Channels supported | mail , database , slack , sms , etc. |