🔹 เกริ่นนำ
ระบบ Notification ของ Laravel ช่วยให้คุณสามารถแจ้งเตือนผู้ใช้ผ่านหลายช่องทางได้ เช่น Email, Slack, SMS หรือฐานข้อมูล ด้วยโค้ดที่สะอาดและปรับขยายได้ง่าย คุณสามารถใช้ Notification เพื่อแจ้งเหตุการณ์สำคัญ เช่น การสมัครสมาชิกใหม่ การชำระเงิน หรือการแจ้งเตือนระบบ
บทนี้จะแนะนำการสร้าง Notification และส่งผ่านช่องทางต่าง ๆ เช่น Email และ Slack
🔸 การสร้าง Notification Class
php artisan make:notification NewUserNotification
จะได้ไฟล์ที่ app/Notifications/NewUserNotification.php
🔸 การส่งผ่าน Email
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
public function toMail($notifiable)
{
return (new MailMessage)
->subject('ยินดีต้อนรับ')
->greeting('สวัสดี')
->line('คุณสมัครสมาชิกเรียบร้อยแล้ว')
->action('เข้าสู่ระบบ', url('/login'));
}
🔸 การส่งผ่าน Slack
use Illuminate\Notifications\Messages\SlackMessage;
public function toSlack($notifiable)
{
return (new SlackMessage)
->success()
->content('มีผู้ใช้ใหม่ลงทะเบียน: ' . $notifiable->name);
}
🔸 การเรียกใช้งาน Notification
use App\Notifications\NewUserNotification;
$user->notify(new NewUserNotification());
🔸 การตั้งค่า Mail และ Slack ใน .env
MAIL_MAILER=smtp
MAIL_HOST=...
MAIL_USERNAME=...
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...
💡 หากใช้หลายช่องทาง Laravel จะเลือก method เช่น
toMail
,toSlack
,toDatabase
ตามลำดับที่กำหนด