📧

Tạo Notification

Multi-channel Notification

php artisan make:notification OrderShipped
<?php
// app/Notifications/OrderShipped.php

namespace App\Notifications;

use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;

class OrderShipped extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public Order $order
    ) {}

    // Channels to use
    public function via(object $notifiable): array
    {
        return ['mail', 'database', 'broadcast', 'slack'];
    }

    // Email notification
    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject('Đơn hàng đã được gửi')
            ->greeting("Xin chào {$notifiable->name}!")
            ->line("Đơn hàng #{$this->order->id} đã được gửi đi.")
            ->line("Mã vận đơn: {$this->order->tracking_number}")
            ->action('Theo dõi đơn hàng', url("/orders/{$this->order->id}"))
            ->line('Cảm ơn bạn đã mua hàng!');
    }

    // Database notification
    public function toDatabase(object $notifiable): array
    {
        return [
            'order_id' => $this->order->id,
            'message' => "Đơn hàng #{$this->order->id} đã được gửi",
            'tracking_number' => $this->order->tracking_number,
        ];
    }

    // Broadcast (realtime)
    public function toBroadcast(object $notifiable): array
    {
        return [
            'order_id' => $this->order->id,
            'message' => "Đơn hàng #{$this->order->id} đã được gửi!",
        ];
    }

    // Slack notification
    public function toSlack(object $notifiable): SlackMessage
    {
        return (new SlackMessage)
            ->success()
            ->content("Đơn hàng #{$this->order->id} đã ship!")
            ->attachment(function ($attachment) {
                $attachment->title('Chi tiết đơn hàng')
                    ->fields([
                        'Khách hàng' => $this->order->user->name,
                        'Tổng tiền' => number_format($this->order->total) . 'đ',
                    ]);
            });
    }
}

// Gửi notification
$user->notify(new OrderShipped($order));

// Gửi cho nhiều users
Notification::send($users, new OrderShipped($order));
💾

Database Notifications

Lưu và Đọc Notifications

# Tạo notifications table
php artisan notifications:table
php artisan migrate
<?php
// Đọc notifications
$notifications = $user->notifications;
$unread = $user->unreadNotifications;

// Đánh dấu đã đọc
$user->unreadNotifications->markAsRead();

// Đánh dấu 1 notification
$notification->markAsRead();

// API endpoint
class NotificationController extends Controller
{
    public function index(Request $request)
    {
        return $request->user()
            ->notifications()
            ->latest()
            ->paginate(20);
    }

    public function markAsRead(Request $request, string $id)
    {
        $notification = $request->user()
            ->notifications()
            ->findOrFail($id);
            
        $notification->markAsRead();

        return response()->json(['success' => true]);
    }

    public function markAllAsRead(Request $request)
    {
        $request->user()->unreadNotifications->markAsRead();
        
        return response()->json(['success' => true]);
    }
}
💡 Realtime: Kết hợp database + broadcast để hiển thị notification realtime trong UI.
← Bài 8: Reverb Bài 10: Factories →