본문 바로가기

알림

업데이트됨

번역일: 2026년 11월 18일

이 페이지는 원문이 업데이트되어 번역이 갱신되었습니다.

원문 수정
2026년 11월 15일
번역 갱신
2026년 11월 18일

알림

소개

Laravel은 이메일 발송 기능과 더불어, 여러 전송 채널로 알림을 보내는 기능을 제공합니다. 기본으로 지원하는 채널에는 이메일, SMS(Vonage, 예전 이름은 Nexmo), Slack이 있습니다. 여기에 더해 커뮤니티에서 만든 다양한 알림 채널을 이용하면 수십 가지 채널로 알림을 보낼 수 있습니다. 알림을 데이터베이스에 저장해 두었다가 웹 화면에 표시하는 것도 가능합니다.

알림은 보통 애플리케이션에서 일어난 일을 사용자에게 알려 주는 짧은 안내 메시지입니다. 예를 들어 결제 애플리케이션을 만들고 있다면, 이메일과 SMS 채널로 "청구서 결제 완료" 알림을 사용자에게 보낼 수 있습니다.

알림 생성하기

Laravel에서는 알림 하나가 클래스 하나로 표현되며, 이 클래스는 보통 app/Notifications 디렉터리에 둡니다. 애플리케이션에 이 디렉터리가 보이지 않더라도 걱정하지 않아도 됩니다. make:notification Artisan 명령어를 실행하면 자동으로 만들어집니다:

php artisan make:notification InvoicePaid

이 명령어는 app/Notifications 디렉터리에 새 알림 클래스를 생성합니다. 각 알림 클래스에는 via 메서드와 함께 toMail, toDatabase 같은 메시지 구성 메서드가 필요한 만큼 들어 있습니다. 이 메서드들은 알림을 해당 채널에 맞는 메시지로 변환하는 역할을 합니다.

알림 보내기

Notifiable 트레이트 사용하기

알림을 보내는 방법은 두 가지입니다. Notifiable 트레이트의 notify 메서드를 사용하거나, Notification 파사드를 사용하는 것입니다. Notifiable 트레이트는 애플리케이션의 App\Models\User 모델에 기본으로 포함되어 있습니다:

<?php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; class User extends Authenticatable { use Notifiable; }

이 트레이트가 제공하는 notify 메서드는 알림 인스턴스를 인자로 받습니다:

use App\Notifications\InvoicePaid; $user->notify(new InvoicePaid($invoice));

NOTE

Notifiable 트레이트는 어떤 모델에든 사용할 수 있습니다. User 모델에만 쓸 수 있는 것이 아닙니다.

Notification 파사드 사용하기

Notification 파사드로 알림을 보낼 수도 있습니다. 이 방식은 사용자 컬렉션처럼 알림을 받을 대상이 여럿일 때 유용합니다. 파사드로 알림을 보내려면 알림을 받을 대상 전체와 알림 인스턴스를 send 메서드에 전달합니다:

use Illuminate\Support\Facades\Notification; Notification::send($users, new InvoicePaid($invoice));

sendNow 메서드를 사용하면 알림을 즉시 보낼 수 있습니다. 이 메서드는 알림이 ShouldQueue 인터페이스를 구현하고 있더라도 큐를 거치지 않고 바로 전송합니다:

Notification::sendNow($developers, new DeploymentCompleted($deployment));

전송 채널 지정하기

모든 알림 클래스에는 알림을 어떤 채널로 전송할지 결정하는 via 메서드가 있습니다. 알림은 mail, database, broadcast, vonage, slack 채널로 보낼 수 있습니다.

NOTE

Telegram이나 Pusher 같은 다른 전송 채널을 사용하고 싶다면 커뮤니티가 운영하는 Laravel Notification Channels 웹사이트를 확인해 보세요.

via 메서드는 $notifiable 인스턴스를 전달받는데, 이는 알림을 받는 대상 클래스의 인스턴스입니다. $notifiable을 활용하면 대상에 따라 알림을 전송할 채널을 다르게 정할 수 있습니다:

/** * 알림을 전송할 채널을 반환합니다. * * @return array<int, string> */ public function via(object $notifiable): array { return $notifiable->prefers_sms ? ['vonage'] : ['mail', 'database']; }

알림을 큐에 넣기

WARNING

알림을 큐에 넣기 전에 큐를 설정하고 워커를 실행해 두어야 합니다.

알림 전송에는 시간이 걸릴 수 있습니다. 특히 채널이 알림을 전달하기 위해 외부 API를 호출해야 하는 경우에 그렇습니다. 애플리케이션의 응답 속도를 높이려면 알림 클래스에 ShouldQueue 인터페이스와 Queueable 트레이트를 추가해 알림이 큐에서 처리되도록 하세요. make:notification 명령어로 생성한 알림에는 이 인터페이스와 트레이트가 이미 임포트되어 있으므로, 알림 클래스에 바로 추가할 수 있습니다:

<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; class InvoicePaid extends Notification implements ShouldQueue { use Queueable; // ... }

알림에 ShouldQueue 인터페이스를 추가했다면, 알림은 평소와 똑같이 보내면 됩니다. Laravel이 클래스의 ShouldQueue 인터페이스를 감지해 알림 전송을 자동으로 큐에 넣습니다:

$user->notify(new InvoicePaid($invoice));

알림을 큐에 넣으면 수신자와 채널의 조합마다 큐 Job이 하나씩 생성됩니다. 예를 들어 수신자가 3명이고 채널이 2개인 알림이라면 Job 6개가 큐에 디스패치됩니다.

알림 지연시키기

알림 전송을 지연시키고 싶다면 알림 인스턴스를 만들 때 delay 메서드를 체이닝하면 됩니다:

$delay = now()->plus(minutes: 10); $user->notify((new InvoicePaid($invoice))->delay($delay));

delay 메서드에 배열을 전달하면 채널별로 지연 시간을 다르게 지정할 수 있습니다:

$user->notify((new InvoicePaid($invoice))->delay([ 'mail' => now()->plus(minutes: 5), 'sms' => now()->plus(minutes: 10), ]));

또는 알림 클래스에 withDelay 메서드를 직접 정의할 수도 있습니다. withDelay 메서드는 채널 이름과 지연 값으로 이루어진 배열을 반환해야 합니다:

/** * 알림의 전송 지연 시간을 결정합니다. * * @return array<string, \Illuminate\Support\Carbon> */ public function withDelay(object $notifiable): array { return [ 'mail' => now()->plus(minutes: 5), 'sms' => now()->plus(minutes: 10), ]; }

알림의 큐 커넥션 지정하기

큐에 넣은 알림은 기본적으로 애플리케이션의 기본 큐 커넥션을 사용합니다. 특정 알림에 다른 커넥션을 사용하고 싶다면 알림의 생성자에서 onConnection 메서드를 호출하세요:

<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; class InvoicePaid extends Notification implements ShouldQueue { use Queueable; /** * 새 알림 인스턴스를 생성합니다. */ public function __construct() { $this->onConnection('redis'); } }

알림이 지원하는 채널마다 사용할 큐 커넥션을 따로 지정하고 싶다면 알림에 viaConnections 메서드를 정의하면 됩니다. 이 메서드는 채널 이름과 큐 커넥션 이름의 쌍으로 이루어진 배열을 반환해야 합니다:

/** * 알림 채널별로 사용할 커넥션을 결정합니다. * * @return array<string, string> */ public function viaConnections(): array { return [ 'mail' => 'redis', 'database' => 'sync', ]; }

알림 채널별 큐 지정하기

알림이 지원하는 채널마다 사용할 큐를 따로 지정하고 싶다면 알림에 viaQueues 메서드를 정의하면 됩니다. 이 메서드는 채널 이름과 큐 이름의 쌍으로 이루어진 배열을 반환해야 합니다:

/** * 알림 채널별로 사용할 큐를 결정합니다. * * @return array<string, string> */ public function viaQueues(): array { return [ 'mail' => 'mail-queue', 'slack' => 'slack-queue', ]; }

큐 알림 Job의 어트리뷰트 지정하기

알림 클래스에 큐 어트리뷰트를 정의하면 내부적으로 실행되는 큐 Job의 동작을 조정할 수 있습니다. 이 어트리뷰트들은 알림을 전송하는 큐 Job에 그대로 상속됩니다:

<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; use Illuminate\Queue\Attributes\FailOnTimeout; use Illuminate\Queue\Attributes\MaxExceptions; use Illuminate\Queue\Attributes\Timeout; use Illuminate\Queue\Attributes\Tries; #[Tries(5)] #[Timeout(120)] #[MaxExceptions(3)] #[FailOnTimeout] class InvoicePaid extends Notification implements ShouldQueue { use Queueable; // ... }

큐에 넣은 알림 데이터의 기밀성과 무결성을 암호화로 보장하고 싶다면 알림 클래스에 ShouldBeEncrypted 인터페이스를 추가하세요:

<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; class InvoicePaid extends Notification implements ShouldQueue, ShouldBeEncrypted { use Queueable; // ... }

이 어트리뷰트들을 알림 클래스에 직접 정의하는 것 외에도, RetryFor 어트리뷰트를 정의하거나 backoff와 retryUntil 메서드를 정의해 큐 알림 Job의 백오프 전략과 재시도 제한 시간을 지정할 수 있습니다:

use DateTime; /** * 알림을 재시도하기 전에 대기할 시간(초)을 계산합니다. */ public function backoff(): int { return 3; } /** * 알림이 타임아웃되어야 하는 시각을 결정합니다. */ public function retryUntil(): DateTime { return now()->plus(minutes: 5); }

NOTE

이러한 Job 어트리뷰트와 메서드에 대한 자세한 내용은 큐 Job 문서를 참고하세요.

큐 알림 미들웨어

큐에 넣은 알림에도 큐 Job과 마찬가지로 미들웨어를 정의할 수 있습니다. 먼저 알림 클래스에 middleware 메서드를 정의하세요. middleware 메서드는 $notifiable과 $channel 변수를 전달받으므로, 알림의 목적지에 따라 반환할 미들웨어를 다르게 구성할 수 있습니다:

use Illuminate\Queue\Middleware\RateLimited; /** * 알림 Job이 통과해야 하는 미들웨어를 반환합니다. * * @return array<int, object> */ public function middleware(object $notifiable, string $channel) { return match ($channel) { 'mail' => [new RateLimited('postmark')], 'slack' => [new RateLimited('slack')], default => [], }; }

큐 알림과 데이터베이스 트랜잭션

데이터베이스 트랜잭션 안에서 큐 알림을 디스패치하면, 트랜잭션이 커밋되기 전에 큐가 알림을 먼저 처리해 버릴 수 있습니다. 이 경우 트랜잭션 중에 모델이나 데이터베이스 레코드에 가한 변경이 아직 데이터베이스에 반영되지 않았을 수 있습니다. 또한 트랜잭션 안에서 생성한 모델이나 레코드가 데이터베이스에 아직 존재하지 않을 수도 있습니다. 알림이 이런 모델에 의존한다면, 큐 알림을 전송하는 Job이 처리될 때 예상치 못한 오류가 발생할 수 있습니다.

큐 커넥션의 after_commit 설정 옵션이 false로 되어 있더라도, 알림을 보낼 때 afterCommit 메서드를 호출하면 해당 큐 알림을 열려 있는 모든 데이터베이스 트랜잭션이 커밋된 뒤에 디스패치하도록 지정할 수 있습니다:

use App\Notifications\InvoicePaid; $user->notify((new InvoicePaid($invoice))->afterCommit());

또는 알림의 생성자에서 afterCommit 메서드를 호출할 수도 있습니다:

<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; class InvoicePaid extends Notification implements ShouldQueue { use Queueable; /** * 새 알림 인스턴스를 생성합니다. */ public function __construct() { $this->afterCommit(); } }

NOTE

이 문제를 우회하는 방법에 대해 더 알아보려면 큐 Job과 데이터베이스 트랜잭션 문서를 참고하세요.

큐 알림의 전송 여부 결정하기

큐 알림이 백그라운드 처리를 위해 큐에 디스패치되면, 보통은 큐 워커가 이를 받아 의도한 수신자에게 전송합니다.

하지만 큐 워커가 알림을 처리하는 시점에 실제로 전송할지 말지를 최종적으로 판단하고 싶다면, 알림 클래스에 shouldSend 메서드를 정의하면 됩니다. 이 메서드가 false를 반환하면 알림은 전송되지 않습니다:

/** * 알림을 전송해야 하는지 결정합니다. */ public function shouldSend(object $notifiable, string $channel): bool { return $this->invoice->isPaid(); }

알림 전송 후 처리

알림이 전송된 뒤에 코드를 실행하고 싶다면 알림 클래스에 afterSending 메서드를 정의하면 됩니다. 이 메서드는 알림을 받은 대상, 채널 이름, 채널의 응답을 전달받습니다:

/** * 알림이 전송된 뒤의 처리를 수행합니다. */ public function afterSending(object $notifiable, string $channel, mixed $response): void { // ... }

온디맨드 알림

애플리케이션의 "사용자"로 저장되어 있지 않은 사람에게 알림을 보내야 할 때가 있습니다. Notification 파사드의 route 메서드를 사용하면 알림을 보내기 전에 임시 라우팅 정보를 지정할 수 있습니다:

use Illuminate\Broadcasting\Channel; use Illuminate\Support\Facades\Notification; Notification::route('mail', 'taylor@example.com') ->route('vonage', '5555555555') ->route('slack', '#slack-channel') ->route('broadcast', [new Channel('channel-name')]) ->notify(new InvoicePaid($invoice));

mail 라우트로 온디맨드 알림을 보낼 때 수신자의 이름도 함께 지정하고 싶다면, 이메일 주소를 키로 하고 이름을 값으로 하는 요소를 배열의 첫 번째 요소로 전달하면 됩니다:

Notification::route('mail', [ 'barrett@example.com' => 'Barrett Blair', ])->notify(new InvoicePaid($invoice));

routes 메서드를 사용하면 여러 알림 채널의 임시 라우팅 정보를 한 번에 지정할 수 있습니다:

Notification::routes([ 'mail' => ['barrett@example.com' => 'Barrett Blair'], 'vonage' => '5555555555', ])->notify(new InvoicePaid($invoice));

메일 알림

메일 메시지 구성하기

알림을 이메일로 보낼 수 있게 하려면 알림 클래스에 toMail 메서드를 정의해야 합니다. 이 메서드는 $notifiable 엔티티를 전달받고 Illuminate\Notifications\Messages\MailMessage 인스턴스를 반환해야 합니다.

MailMessage 클래스에는 트랜잭션 이메일 메시지를 만드는 데 도움이 되는 간단한 메서드가 몇 가지 들어 있습니다. 메일 메시지에는 여러 줄의 텍스트와 "콜 투 액션(call to action)" 버튼을 담을 수 있습니다. toMail 메서드의 예시를 살펴보겠습니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { $url = url('/invoice/'.$this->invoice->id); return (new MailMessage) ->greeting('안녕하세요!') ->line('청구서 한 건의 결제가 완료되었습니다!') ->lineIf($this->amount > 0, "결제 금액: {$this->amount}") ->action('청구서 보기', $url) ->line('저희 애플리케이션을 이용해 주셔서 감사합니다!'); }

NOTE

toMail 메서드에서 $this->invoice->id를 사용하고 있다는 점에 주목하세요. 알림이 메시지를 만드는 데 필요한 데이터는 무엇이든 알림의 생성자로 전달할 수 있습니다.

이 예시에서는 인사말, 텍스트 한 줄, 콜 투 액션, 그리고 또 다른 텍스트 한 줄을 등록합니다. MailMessage 객체가 제공하는 이 메서드들 덕분에 간단한 트랜잭션 이메일을 쉽고 빠르게 구성할 수 있습니다. 그러면 메일 채널이 메시지 구성 요소를 보기 좋은 반응형 HTML 이메일 템플릿과 그에 대응하는 일반 텍스트 버전으로 변환합니다. 다음은 mail 채널이 생성한 이메일의 예시입니다:

NOTE

메일 알림을 보낼 때는 config/app.php 설정 파일의 name 설정 옵션을 반드시 지정해 두세요. 이 값은 메일 알림 메시지의 헤더와 푸터에 사용됩니다.

오류 메시지

청구서 결제 실패처럼 사용자에게 오류를 알리는 알림도 있습니다. 메시지를 구성할 때 error 메서드를 호출하면 해당 메일 메시지가 오류에 관한 것임을 나타낼 수 있습니다. 메일 메시지에 error 메서드를 사용하면 콜 투 액션 버튼이 검은색 대신 빨간색으로 표시됩니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->error() ->subject('청구서 결제 실패') ->line('...'); }

그 밖의 메일 알림 구성 옵션

알림 클래스에 텍스트 "줄"을 정의하는 대신, view 메서드로 알림 이메일을 렌더링할 커스텀 템플릿을 지정할 수 있습니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage)->view( 'mail.invoice.paid', ['invoice' => $this->invoice] ); }

view 메서드에 배열을 전달하고 그 두 번째 요소로 뷰 이름을 넘기면 메일 메시지의 일반 텍스트 뷰를 지정할 수 있습니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage)->view( ['mail.invoice.paid', 'mail.invoice.paid-text'], ['invoice' => $this->invoice] ); }

메시지에 일반 텍스트 뷰만 있다면 text 메서드를 사용할 수 있습니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage)->text( 'mail.invoice.paid-text', ['invoice' => $this->invoice] ); }

발신자 변경하기

이메일의 발신자(from) 주소는 기본적으로 config/mail.php 설정 파일에 정의되어 있습니다. 하지만 from 메서드를 사용하면 특정 알림의 발신 주소를 따로 지정할 수 있습니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->from('barrett@example.com', 'Barrett Blair') ->line('...'); }

수신자 변경하기

mail 채널로 알림을 보낼 때 알림 시스템은 알림을 받는 엔티티에서 email 프로퍼티를 자동으로 찾습니다. 알림을 받는 엔티티에 routeNotificationForMail 메서드를 정의하면 알림 전달에 사용할 이메일 주소를 직접 지정할 수 있습니다:

<?php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notification; class User extends Authenticatable { use Notifiable; /** * 메일 채널의 알림 라우팅 정보를 반환합니다. * * @return array<string, string>|string */ public function routeNotificationForMail(Notification $notification): array|string { // 이메일 주소만 반환하는 경우... return $this->email_address; // 이메일 주소와 이름을 함께 반환하는 경우... return [$this->email_address => $this->name]; } }

제목 변경하기

이메일 제목은 기본적으로 알림 클래스 이름을 "Title Case"로 변환한 값입니다. 따라서 알림 클래스 이름이 InvoicePaid라면 이메일 제목은 Invoice Paid가 됩니다. 메시지에 다른 제목을 지정하고 싶다면 메시지를 구성할 때 subject 메서드를 호출하면 됩니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->subject('알림 제목') ->line('...'); }

메일러 변경하기

이메일 알림은 기본적으로 config/mail.php 설정 파일에 정의된 기본 메일러로 전송됩니다. 하지만 메시지를 구성할 때 mailer 메서드를 호출하면 런타임에 다른 메일러를 지정할 수 있습니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->mailer('postmark') ->line('...'); }

템플릿 변경하기

알림 패키지의 리소스를 퍼블리시하면 메일 알림에 사용되는 HTML 템플릿과 일반 텍스트 템플릿을 수정할 수 있습니다. 아래 명령어를 실행하면 메일 알림 템플릿이 resources/views/vendor/notifications 디렉터리에 생성됩니다:

php artisan vendor:publish --tag=laravel-notifications

첨부 파일

이메일 알림에 첨부 파일을 추가하려면 메시지를 구성할 때 attach 메서드를 사용하세요. attach 메서드는 첫 번째 인자로 파일의 절대 경로를 받습니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->greeting('안녕하세요!') ->attach('/path/to/file'); }

NOTE

알림 메일 메시지의 attach 메서드는 첨부 가능 객체도 받을 수 있습니다. 자세한 내용은 첨부 가능 객체 문서를 참고하세요.

메시지에 파일을 첨부할 때 attach 메서드의 두 번째 인자로 array를 전달하면 표시 이름이나 MIME 타입, 또는 둘 다를 지정할 수 있습니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->greeting('안녕하세요!') ->attach('/path/to/file', [ 'as' => 'name.pdf', 'mime' => 'application/pdf', ]); }

필요하다면 attachMany 메서드로 메시지에 여러 파일을 한꺼번에 첨부할 수 있습니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->greeting('안녕하세요!') ->attachMany([ '/path/to/forge.svg', '/path/to/vapor.svg' => [ 'as' => 'Logo.svg', 'mime' => 'image/svg+xml', ], ]); }

attachFromStorageDisk 메서드를 사용하면 특정 파일시스템 디스크에 있는 파일을 첨부할 수 있습니다. 이 메서드는 디스크 이름과 해당 디스크 내 파일 경로를 받습니다:

use App\Mail\InvoicePaid as InvoicePaidMailable; /** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): Mailable { return (new InvoicePaidMailable($this->invoice)) ->to($notifiable->email) ->attachFromStorageDisk('s3', '/path/to/file', 'invoice.pdf', [ 'mime' => 'application/pdf', ]); }

원시 데이터 첨부

attachData 메서드를 사용하면 원시 바이트 문자열을 첨부 파일로 추가할 수 있습니다. attachData 메서드를 호출할 때는 첨부 파일에 붙일 파일 이름을 함께 전달해야 합니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->greeting('안녕하세요!') ->attachData($this->pdf, 'name.pdf', [ 'mime' => 'application/pdf', ]); }

태그와 메타데이터 추가하기

Mailgun, Postmark 같은 일부 서드파티 이메일 서비스는 메시지 "태그"와 "메타데이터"를 지원합니다. 이를 이용하면 애플리케이션이 보낸 이메일을 그룹으로 묶고 추적할 수 있습니다. 이메일 메시지에 태그와 메타데이터를 추가하려면 tag와 metadata 메서드를 사용합니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->greeting('댓글이 추천을 받았습니다!') ->tag('upvote') ->metadata('comment_id', $this->comment->id); }

애플리케이션에서 Mailgun 드라이버를 사용한다면 Mailgun 문서에서 태그와 메타데이터에 대한 자세한 내용을 확인할 수 있습니다. 마찬가지로 Postmark 문서에서도 태그와 메타데이터 지원에 대한 자세한 내용을 확인할 수 있습니다.

애플리케이션이 Amazon SES로 이메일을 보낸다면 metadata 메서드를 사용해 메시지에 SES "태그"를 붙여야 합니다.

Symfony 메시지 커스터마이징

MailMessage 클래스의 withSymfonyMessage 메서드를 사용하면 메시지를 보내기 전에 Symfony Message 인스턴스와 함께 호출될 클로저를 등록할 수 있습니다. 이를 통해 메시지가 전달되기 전에 세밀하게 커스터마이징할 수 있습니다:

use Symfony\Component\Mime\Email; /** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->withSymfonyMessage(function (Email $message) { $message->getHeaders()->addTextHeader( 'Custom-Header', 'Header Value' ); }); }

Mailable 사용하기

필요하다면 알림의 toMail 메서드에서 완전한 mailable 객체를 반환할 수 있습니다. MailMessage 대신 Mailable을 반환할 때는 mailable 객체의 to 메서드로 메시지 수신자를 지정해야 합니다:

use App\Mail\InvoicePaid as InvoicePaidMailable; use Illuminate\Mail\Mailable; /** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): Mailable { return (new InvoicePaidMailable($this->invoice)) ->to($notifiable->email); }

Mailable과 온디맨드 알림

온디맨드 알림을 보내는 경우 toMail 메서드에 전달되는 $notifiable 인스턴스는 Illuminate\Notifications\AnonymousNotifiable의 인스턴스입니다. 이 클래스가 제공하는 routeNotificationFor 메서드로 온디맨드 알림을 보낼 이메일 주소를 가져올 수 있습니다:

use App\Mail\InvoicePaid as InvoicePaidMailable; use Illuminate\Notifications\AnonymousNotifiable; use Illuminate\Mail\Mailable; /** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): Mailable { $address = $notifiable instanceof AnonymousNotifiable ? $notifiable->routeNotificationFor('mail') : $notifiable->email; return (new InvoicePaidMailable($this->invoice)) ->to($address); }

메일 알림 미리보기

메일 알림 템플릿을 디자인할 때는 일반 Blade 템플릿처럼 렌더링된 메일 메시지를 브라우저에서 바로 미리 볼 수 있으면 편리합니다. 그래서 Laravel에서는 메일 알림이 생성한 메일 메시지를 라우트 클로저나 컨트롤러에서 그대로 반환할 수 있습니다. MailMessage를 반환하면 렌더링되어 브라우저에 표시되므로, 실제 이메일 주소로 보내지 않고도 디자인을 빠르게 확인할 수 있습니다:

use App\Models\Invoice; use App\Notifications\InvoicePaid; Route::get('/notification', function () { $invoice = Invoice::find(1); return (new InvoicePaid($invoice)) ->toMail($invoice->user); });

마크다운 메일 알림

마크다운 메일 알림을 사용하면 메일 알림에 미리 만들어져 있는 템플릿을 그대로 활용하면서도, 더 길고 자유로운 형태의 메시지를 작성할 수 있습니다. 메시지를 마크다운으로 작성하므로 Laravel이 보기 좋은 반응형 HTML 템플릿으로 렌더링해 주고, 그에 대응하는 일반 텍스트 버전도 자동으로 생성합니다.

메시지 생성하기

마크다운 템플릿이 함께 딸린 알림을 생성하려면 make:notification Artisan 명령어의 --markdown 옵션을 사용합니다:

php artisan make:notification InvoicePaid --markdown=mail.invoice.paid

다른 메일 알림과 마찬가지로, 마크다운 템플릿을 사용하는 알림도 알림 클래스에 toMail 메서드를 정의해야 합니다. 다만 line과 action 메서드로 알림을 구성하는 대신 markdown 메서드로 사용할 마크다운 템플릿의 이름을 지정합니다. 템플릿에서 사용할 데이터 배열은 이 메서드의 두 번째 인자로 전달할 수 있습니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { $url = url('/invoice/'.$this->invoice->id); return (new MailMessage) ->subject('청구서 결제 완료') ->markdown('mail.invoice.paid', ['url' => $url]); }

메시지 작성하기

마크다운 메일 알림은 Blade 컴포넌트와 마크다운 문법을 함께 사용합니다. 덕분에 Laravel이 미리 만들어 둔 알림 컴포넌트를 활용하면서 알림을 손쉽게 구성할 수 있습니다:

<x-mail::message> # 청구서 결제 완료 청구서 결제가 완료되었습니다! <x-mail::button :url="$url"> 청구서 보기 </x-mail::button> 감사합니다.<br> {{ config('app.name') }} </x-mail::message>

NOTE

마크다운 이메일을 작성할 때는 들여쓰기를 과하게 넣지 마세요. 마크다운 표준에 따라 마크다운 파서는 들여쓴 내용을 코드 블록으로 렌더링합니다.

버튼 컴포넌트

버튼 컴포넌트는 가운데 정렬된 버튼 링크를 렌더링합니다. 이 컴포넌트는 url과 선택 사항인 color, 두 가지 인자를 받습니다. 지원하는 색상은 primary, green, red입니다. 버튼 컴포넌트는 알림 하나에 원하는 만큼 추가할 수 있습니다:

<x-mail::button :url="$url" color="green"> 청구서 보기 </x-mail::button>

패널 컴포넌트

패널 컴포넌트는 주어진 텍스트 블록을 알림의 나머지 부분과 배경색이 살짝 다른 패널 안에 렌더링합니다. 특정 텍스트 블록에 시선을 끌고 싶을 때 사용합니다:

<x-mail::panel> 패널에 들어갈 내용입니다. </x-mail::panel>

테이블 컴포넌트

테이블 컴포넌트는 마크다운 표를 HTML 테이블로 변환해 줍니다. 이 컴포넌트는 마크다운 표를 콘텐츠로 받습니다. 열 정렬은 마크다운의 기본 표 정렬 문법으로 지정할 수 있습니다:

<x-mail::table> | Laravel | Table | Example | | ------------- | :-----------: | ------------: | | Col 2 is | Centered | $10 | | Col 3 is | Right-Aligned | $20 | </x-mail::table>

컴포넌트 커스터마이징

마크다운 알림 컴포넌트를 모두 애플리케이션으로 내보내 원하는 대로 수정할 수 있습니다. 컴포넌트를 내보내려면 vendor:publish Artisan 명령어로 laravel-mail 에셋 태그를 퍼블리시하세요:

php artisan vendor:publish --tag=laravel-mail

이 명령어는 마크다운 메일 컴포넌트를 resources/views/vendor/mail 디렉터리에 퍼블리시합니다. mail 디렉터리에는 html 디렉터리와 text 디렉터리가 있고, 각각 사용 가능한 모든 컴포넌트의 해당 형식 버전이 들어 있습니다. 이 컴포넌트들은 자유롭게 수정해도 됩니다.

CSS 커스터마이징

컴포넌트를 내보내고 나면 resources/views/vendor/mail/html/themes 디렉터리에 default.css 파일이 생깁니다. 이 파일의 CSS를 수정하면 해당 스타일이 마크다운 알림의 HTML 버전에 자동으로 인라인 처리됩니다.

Laravel의 마크다운 컴포넌트에 쓸 완전히 새로운 테마를 만들고 싶다면 html/themes 디렉터리에 CSS 파일을 추가하면 됩니다. CSS 파일에 이름을 붙여 저장한 뒤, mail 설정 파일의 theme 옵션을 새 테마 이름으로 바꿔 주세요.

개별 알림의 테마만 바꾸고 싶다면 알림의 메일 메시지를 구성할 때 theme 메서드를 호출하면 됩니다. theme 메서드는 알림을 보낼 때 사용할 테마의 이름을 받습니다:

/** * 알림의 메일 표현을 반환합니다. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->theme('invoice') ->subject('청구서 결제 완료') ->markdown('mail.invoice.paid', ['url' => $url]); }

데이터베이스 알림

사전 준비

database 알림 채널은 알림 정보를 데이터베이스 테이블에 저장합니다. 이 테이블에는 알림 타입과 함께, 알림 내용을 설명하는 JSON 데이터 구조 같은 정보가 담깁니다.

이 테이블을 조회하면 애플리케이션의 사용자 인터페이스에 알림을 표시할 수 있습니다. 그 전에 먼저 알림을 저장할 데이터베이스 테이블을 만들어야 합니다. make:notifications-table 명령어를 사용하면 알맞은 테이블 스키마가 담긴 마이그레이션을 생성할 수 있습니다:

php artisan make:notifications-tablephp artisan migrate

NOTE

알림을 받는 모델이 UUID 또는 ULID 기본 키를 사용한다면, 알림 테이블 마이그레이션에서 morphs 메서드를 uuidMorphs 또는 ulidMorphs로 바꿔야 합니다.

데이터베이스 알림 구성하기

알림을 데이터베이스 테이블에 저장할 수 있게 하려면 알림 클래스에 toDatabase 또는 toArray 메서드를 정의해야 합니다. 이 메서드는 $notifiable 엔티티를 전달받고 일반 PHP 배열을 반환해야 합니다. 반환된 배열은 JSON으로 인코딩되어 notifications 테이블의 data 컬럼에 저장됩니다. toArray 메서드의 예시를 살펴보겠습니다:

/** * 알림의 배열 표현을 반환합니다. * * @return array<string, mixed> */ public function toArray(object $notifiable): array { return [ 'invoice_id' => $this->invoice->id, 'amount' => $this->invoice->amount, ]; }

알림이 애플리케이션의 데이터베이스에 저장될 때 type 컬럼은 기본적으로 알림의 클래스 이름으로 설정되고, read_at 컬럼은 null이 됩니다. 알림 클래스에 databaseType과 initialDatabaseReadAtValue 메서드를 정의하면 이 동작을 바꿀 수 있습니다:

use Illuminate\Support\Carbon; /** * 알림의 데이터베이스 타입을 반환합니다. */ public function databaseType(object $notifiable): string { return 'invoice-paid'; } /** * "read_at" 컬럼의 초기값을 반환합니다. */ public function initialDatabaseReadAtValue(): ?Carbon { return null; }

`toDatabase` vs. `toArray`

toArray 메서드는 broadcast 채널에서도 사용되며, JavaScript 기반 프런트엔드로 어떤 데이터를 브로드캐스트할지 결정합니다. database 채널과 broadcast 채널에 서로 다른 배열 표현을 쓰고 싶다면 toArray 메서드 대신 toDatabase 메서드를 정의해야 합니다.

알림 조회하기

알림이 데이터베이스에 저장되고 나면, 알림을 받는 엔티티에서 이를 편리하게 조회할 방법이 필요합니다. Laravel의 기본 App\Models\User 모델에 포함된 Illuminate\Notifications\Notifiable 트레이트에는 해당 엔티티의 알림을 반환하는 notifications Eloquent 연관관계가 들어 있습니다. 알림을 가져오려면 다른 Eloquent 연관관계와 똑같이 이 메서드에 접근하면 됩니다. 알림은 기본적으로 created_at 타임스탬프 기준으로 정렬되며, 가장 최근 알림이 컬렉션의 맨 앞에 옵니다:

$user = App\Models\User::find(1); foreach ($user->notifications as $notification) { echo $notification->type; }

"읽지 않은" 알림만 가져오고 싶다면 unreadNotifications 연관관계를 사용하면 됩니다. 이 알림들 역시 created_at 타임스탬프 기준으로 정렬되며, 가장 최근 알림이 컬렉션의 맨 앞에 옵니다:

$user = App\Models\User::find(1); foreach ($user->unreadNotifications as $notification) { echo $notification->type; }

"읽은" 알림만 가져오고 싶다면 readNotifications 연관관계를 사용하면 됩니다:

$user = App\Models\User::find(1); foreach ($user->readNotifications as $notification) { echo $notification->type; }

NOTE

JavaScript 클라이언트에서 알림을 조회하려면, 현재 사용자처럼 알림을 받는 엔티티의 알림을 반환하는 알림 컨트롤러를 애플리케이션에 정의해야 합니다. 그런 다음 JavaScript 클라이언트에서 해당 컨트롤러의 URL로 HTTP 요청을 보내면 됩니다.

알림을 읽음으로 표시하기

보통은 사용자가 알림을 확인했을 때 해당 알림을 "읽음"으로 표시하게 됩니다. Illuminate\Notifications\Notifiable 트레이트는 markAsRead 메서드를 제공하며, 이 메서드는 알림의 데이터베이스 레코드에서 read_at 컬럼을 갱신합니다:

$user = App\Models\User::find(1); foreach ($user->unreadNotifications as $notification) { $notification->markAsRead(); }

알림을 하나씩 순회하는 대신, 알림 컬렉션에 markAsRead 메서드를 바로 호출할 수도 있습니다:

$user->unreadNotifications->markAsRead();

대량 업데이트 쿼리를 사용하면 알림을 데이터베이스에서 조회하지 않고도 모든 알림을 읽음으로 표시할 수 있습니다:

$user = App\Models\User::find(1); $user->unreadNotifications()->update(['read_at' => now()]);

알림을 delete하면 테이블에서 완전히 제거할 수 있습니다:

$user->notifications()->delete();

브로드캐스트 알림

사전 준비

알림을 브로드캐스트하기 전에 Laravel의 이벤트 브로드캐스팅 서비스를 설정하고 그 사용법을 익혀 두어야 합니다. 이벤트 브로드캐스팅은 JavaScript 기반 프런트엔드에서 서버 측 Laravel 이벤트에 반응할 수 있게 해 주는 기능입니다.

브로드캐스트 알림 구성하기

broadcast 채널은 Laravel의 이벤트 브로드캐스팅 서비스를 사용해 알림을 브로드캐스트하므로, JavaScript 기반 프런트엔드에서 알림을 실시간으로 받을 수 있습니다. 알림이 브로드캐스팅을 지원하게 하려면 알림 클래스에 toBroadcast 메서드를 정의하면 됩니다. 이 메서드는 $notifiable 엔티티를 전달받고 BroadcastMessage 인스턴스를 반환해야 합니다. toBroadcast 메서드가 없으면 toArray 메서드로 브로드캐스트할 데이터를 수집합니다. 반환된 데이터는 JSON으로 인코딩되어 JavaScript 기반 프런트엔드로 브로드캐스트됩니다. toBroadcast 메서드의 예시를 살펴보겠습니다:

use Illuminate\Notifications\Messages\BroadcastMessage; /** * 알림의 브로드캐스트용 표현을 반환합니다. */ public function toBroadcast(object $notifiable): BroadcastMessage { return new BroadcastMessage([ 'invoice_id' => $this->invoice->id, 'amount' => $this->invoice->amount, ]); }

브로드캐스트 큐 설정

모든 브로드캐스트 알림은 큐에 넣어진 뒤 브로드캐스트됩니다. 브로드캐스트 작업을 큐에 넣을 때 사용할 큐 커넥션이나 큐 이름을 지정하고 싶다면 BroadcastMessage의 onConnection과 onQueue 메서드를 사용하면 됩니다:

return (new BroadcastMessage($data)) ->onConnection('sqs') ->onQueue('broadcasts');

알림 타입 변경하기

모든 브로드캐스트 알림에는 직접 지정한 데이터 외에도 알림의 전체 클래스 이름이 담긴 type 필드가 포함됩니다. 알림의 type을 바꾸고 싶다면 알림 클래스에 broadcastType 메서드를 정의하면 됩니다:

/** * 브로드캐스트되는 알림의 타입을 반환합니다. */ public function broadcastType(): string { return 'broadcast.message'; }

알림 수신하기

알림은 {notifiable}.{id} 규칙으로 이름이 붙은 프라이빗 채널로 브로드캐스트됩니다. 따라서 ID가 1인 App\Models\User 인스턴스에 알림을 보내면, 알림은 App.Models.User.1 프라이빗 채널로 브로드캐스트됩니다. Laravel Echo를 사용한다면 notification 메서드로 채널의 알림을 간단히 수신할 수 있습니다:

Echo.private('App.Models.User.' + userId) .notification((notification) => { console.log(notification.type); });

React, Vue, Svelte 사용하기

Laravel Echo에는 알림 수신을 간편하게 해 주는 React, Vue, Svelte 훅이 포함되어 있습니다. 먼저 알림을 수신하는 데 쓰이는 useEchoNotification 훅을 호출하세요. useEchoNotification 훅은 이를 사용하는 컴포넌트가 언마운트될 때 채널에서 자동으로 나갑니다:

React

import { useEchoNotification } from "@laravel/echo-react"; useEchoNotification( `App.Models.User.${userId}`, (notification) => { console.log(notification.type); }, );

Vue

<script setup lang="ts"> import { useEchoNotification } from "@laravel/echo-vue"; useEchoNotification( `App.Models.User.${userId}`, (notification) => { console.log(notification.type); }, ); </script>

Svelte

<script> import { useEchoNotification } from "@laravel/echo-svelte"; useEchoNotification( `App.Models.User.${userId}`, (notification) => { console.log(notification.type); }, ); </script>

이 훅은 기본적으로 모든 알림을 수신합니다. 수신할 알림 타입을 지정하려면 useEchoNotification에 타입을 문자열 하나 또는 배열로 전달하면 됩니다:

React

import { useEchoNotification } from "@laravel/echo-react"; useEchoNotification( `App.Models.User.${userId}`, (notification) => { console.log(notification.type); }, 'App.Notifications.InvoicePaid', );

Vue

<script setup lang="ts"> import { useEchoNotification } from "@laravel/echo-vue"; useEchoNotification( `App.Models.User.${userId}`, (notification) => { console.log(notification.type); }, 'App.Notifications.InvoicePaid', ); </script>

Svelte

<script> import { useEchoNotification } from "@laravel/echo-svelte"; useEchoNotification( `App.Models.User.${userId}`, (notification) => { console.log(notification.type); }, 'App.Notifications.InvoicePaid', ); </script>

알림 페이로드 데이터의 형태를 지정할 수도 있습니다. 이렇게 하면 타입 안전성이 높아지고 편집도 한결 편해집니다:

type InvoicePaidNotification = { invoice_id: number; created_at: string; }; useEchoNotification<InvoicePaidNotification>( `App.Models.User.${userId}`, (notification) => { console.log(notification.invoice_id); console.log(notification.created_at); console.log(notification.type); }, 'App.Notifications.InvoicePaid', );

알림 채널 변경하기

엔티티의 브로드캐스트 알림이 어떤 채널로 브로드캐스트될지 직접 정하고 싶다면, 알림을 받는 엔티티에 receivesBroadcastNotificationsOn 메서드를 정의하면 됩니다:

<?php namespace App\Models; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; class User extends Authenticatable { use Notifiable; /** * 사용자가 알림 브로드캐스트를 수신하는 채널을 반환합니다. */ public function receivesBroadcastNotificationsOn(): string { return 'users.'.$this->id; } }

SMS 알림

사전 준비

Laravel의 SMS 알림 전송은 Vonage(예전 이름은 Nexmo)를 기반으로 동작합니다. Vonage로 알림을 보내려면 먼저 laravel/vonage-notification-channel과 guzzlehttp/guzzle 패키지를 설치해야 합니다:

composer require laravel/vonage-notification-channel guzzlehttp/guzzle

이 패키지에는 설정 파일이 포함되어 있습니다. 하지만 이 설정 파일을 애플리케이션으로 꼭 내보내야 하는 것은 아닙니다. VONAGE_KEY와 VONAGE_SECRET 환경 변수에 Vonage 공개 키와 시크릿 키를 정의하기만 하면 됩니다.

키를 정의한 다음에는 SMS 메시지를 보낼 때 기본으로 사용할 발신 전화번호를 VONAGE_SMS_FROM 환경 변수에 지정해야 합니다. 이 전화번호는 Vonage 제어판에서 발급받을 수 있습니다:

VONAGE_SMS_FROM=15556666666

SMS 알림 구성하기

알림을 SMS로 보낼 수 있게 하려면 알림 클래스에 toVonage 메서드를 정의해야 합니다. 이 메서드는 $notifiable 엔티티를 전달받고 Illuminate\Notifications\Messages\VonageMessage 인스턴스를 반환해야 합니다:

use Illuminate\Notifications\Messages\VonageMessage; /** * 알림의 Vonage / SMS 표현을 반환합니다. */ public function toVonage(object $notifiable): VonageMessage { return (new VonageMessage) ->content('Your SMS message content'); }

유니코드 콘텐츠

SMS 메시지에 유니코드 문자가 포함된다면 VonageMessage 인스턴스를 구성할 때 unicode 메서드를 호출해야 합니다. 한글 메시지도 유니코드 문자이므로 여기에 해당합니다:

use Illuminate\Notifications\Messages\VonageMessage; /** * 알림의 Vonage / SMS 표현을 반환합니다. */ public function toVonage(object $notifiable): VonageMessage { return (new VonageMessage) ->content('유니코드 문자가 포함된 메시지') ->unicode(); }

"발신" 번호 변경하기

일부 알림을 VONAGE_SMS_FROM 환경 변수에 지정한 번호가 아닌 다른 전화번호로 보내고 싶다면 VonageMessage 인스턴스의 from 메서드를 호출하면 됩니다:

use Illuminate\Notifications\Messages\VonageMessage; /** * 알림의 Vonage / SMS 표현을 반환합니다. */ public function toVonage(object $notifiable): VonageMessage { return (new VonageMessage) ->content('Your SMS message content') ->from('15554443333'); }

클라이언트 참조값 추가하기

사용자별, 팀별, 고객별로 비용을 추적하고 싶다면 알림에 "클라이언트 참조값(client reference)"을 추가할 수 있습니다. Vonage에서는 이 클라이언트 참조값으로 리포트를 생성할 수 있으므로, 특정 고객의 SMS 사용량을 더 잘 파악할 수 있습니다. 클라이언트 참조값으로는 최대 40자의 문자열을 사용할 수 있습니다:

use Illuminate\Notifications\Messages\VonageMessage; /** * 알림의 Vonage / SMS 표현을 반환합니다. */ public function toVonage(object $notifiable): VonageMessage { return (new VonageMessage) ->clientReference((string) $notifiable->id) ->content('Your SMS message content'); }

SMS 알림 라우팅

Vonage 알림이 올바른 전화번호로 전달되게 하려면 알림을 받는 엔티티에 routeNotificationForVonage 메서드를 정의하세요:

<?php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notification; class User extends Authenticatable { use Notifiable; /** * Vonage 채널의 알림 라우팅 정보를 반환합니다. */ public function routeNotificationForVonage(Notification $notification): string { return $this->phone_number; } }

Slack 알림

사전 준비

Slack 알림을 보내기 전에 Composer로 Slack 알림 채널을 설치해야 합니다:

composer require laravel/slack-notification-channel

또한 Slack 워크스페이스에 사용할 Slack App을 만들어야 합니다.

App을 만든 것과 같은 Slack 워크스페이스에만 알림을 보내면 된다면, App에 chat:write, chat:write.public, chat:write.customize 스코프가 있는지 확인하세요. 이 스코프들은 Slack의 App 관리 화면에 있는 "OAuth & Permissions" 탭에서 추가할 수 있습니다.

다음으로 App의 "Bot User OAuth Token"을 복사해 애플리케이션의 services.php 설정 파일에 있는 slack 설정 배열에 넣습니다. 이 토큰은 Slack의 "OAuth & Permissions" 탭에서 확인할 수 있습니다:

'slack' => [ 'notifications' => [ 'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'), 'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'), ], ],

App 배포

애플리케이션이 사용자들이 소유한 외부 Slack 워크스페이스로 알림을 보내야 한다면 Slack을 통해 App을 "배포(distribute)"해야 합니다. App 배포는 Slack에서 App의 "Manage Distribution" 탭에서 관리할 수 있습니다. App을 배포하고 나면 Socialite를 사용해 애플리케이션 사용자를 대신하여 Slack Bot 토큰을 발급받을 수 있습니다.

Slack 알림 구성하기

알림을 Slack 메시지로 보낼 수 있게 하려면 알림 클래스에 toSlack 메서드를 정의해야 합니다. 이 메서드는 $notifiable 엔티티를 전달받고 Illuminate\Notifications\Slack\SlackMessage 인스턴스를 반환해야 합니다. Slack의 Block Kit API를 사용하면 풍부한 형태의 알림을 구성할 수 있습니다. 다음 예시는 Slack의 Block Kit 빌더에서 미리 볼 수 있습니다:

use Illuminate\Notifications\Slack\BlockKit\Blocks\ContextBlock; use Illuminate\Notifications\Slack\BlockKit\Blocks\SectionBlock; use Illuminate\Notifications\Slack\SlackMessage; /** * 알림의 Slack 표현을 반환합니다. */ public function toSlack(object $notifiable): SlackMessage { return (new SlackMessage) ->text('One of your invoices has been paid!') ->headerBlock('Invoice Paid') ->contextBlock(function (ContextBlock $block) { $block->text('Customer #1234'); }) ->sectionBlock(function (SectionBlock $block) { $block->text('An invoice has been paid.'); $block->field("*Invoice No:*\n1000")->markdown(); $block->field("*Invoice Recipient:*\ntaylor@laravel.com")->markdown(); }) ->dividerBlock() ->sectionBlock(function (SectionBlock $block) { $block->text('Congratulations!'); }); }

Slack의 Block Kit 빌더 템플릿 사용하기

플루언트 메시지 빌더 메서드로 Block Kit 메시지를 구성하는 대신, Slack의 Block Kit 빌더가 생성한 원시 JSON 페이로드를 usingBlockKitTemplate 메서드에 그대로 전달할 수도 있습니다:

use Illuminate\Notifications\Slack\SlackMessage; use Illuminate\Support\Str; /** * 알림의 Slack 표현을 반환합니다. */ public function toSlack(object $notifiable): SlackMessage { $template = <<<JSON { "blocks": [ { "type": "header", "text": { "type": "plain_text", "text": "Team Announcement" } }, { "type": "section", "text": { "type": "plain_text", "text": "We are hiring!" } } ] } JSON; return (new SlackMessage) ->usingBlockKitTemplate($template); }

Slack 상호작용

Slack의 Block Kit 알림 시스템은 사용자 상호작용을 처리하는 강력한 기능을 제공합니다. 이 기능을 사용하려면 Slack App에서 "Interactivity"를 활성화하고, 애플리케이션이 제공하는 URL을 가리키는 "Request URL"을 설정해야 합니다. 이 설정은 Slack의 App 관리 화면에 있는 "Interactivity & Shortcuts" 탭에서 관리할 수 있습니다.

actionsBlock 메서드를 사용하는 아래 예시에서, Slack은 버튼을 클릭한 Slack 사용자, 클릭된 버튼의 ID 등이 담긴 페이로드와 함께 "Request URL"로 POST 요청을 보냅니다. 애플리케이션은 이 페이로드를 바탕으로 어떤 동작을 수행할지 결정할 수 있습니다. 이때 해당 요청이 정말 Slack에서 보낸 것인지도 검증해야 합니다:

use Illuminate\Notifications\Slack\BlockKit\Blocks\ActionsBlock; use Illuminate\Notifications\Slack\BlockKit\Blocks\ContextBlock; use Illuminate\Notifications\Slack\BlockKit\Blocks\SectionBlock; use Illuminate\Notifications\Slack\SlackMessage; /** * 알림의 Slack 표현을 반환합니다. */ public function toSlack(object $notifiable): SlackMessage { return (new SlackMessage) ->text('One of your invoices has been paid!') ->headerBlock('Invoice Paid') ->contextBlock(function (ContextBlock $block) { $block->text('Customer #1234'); }) ->sectionBlock(function (SectionBlock $block) { $block->text('An invoice has been paid.'); }) ->actionsBlock(function (ActionsBlock $block) { // ID는 기본적으로 "button_acknowledge_invoice"가 됩니다... $block->button('Acknowledge Invoice')->primary(); // ID를 직접 지정하는 경우... $block->button('Deny')->danger()->id('deny_invoice'); }); }

확인 모달

동작이 수행되기 전에 사용자가 반드시 확인을 거치게 하고 싶다면 버튼을 정의할 때 confirm 메서드를 호출하면 됩니다. confirm 메서드는 메시지와, ConfirmObject 인스턴스를 전달받는 클로저를 인자로 받습니다:

use Illuminate\Notifications\Slack\BlockKit\Blocks\ActionsBlock; use Illuminate\Notifications\Slack\BlockKit\Blocks\ContextBlock; use Illuminate\Notifications\Slack\BlockKit\Blocks\SectionBlock; use Illuminate\Notifications\Slack\BlockKit\Composites\ConfirmObject; use Illuminate\Notifications\Slack\SlackMessage; /** * 알림의 Slack 표현을 반환합니다. */ public function toSlack(object $notifiable): SlackMessage { return (new SlackMessage) ->text('One of your invoices has been paid!') ->headerBlock('Invoice Paid') ->contextBlock(function (ContextBlock $block) { $block->text('Customer #1234'); }) ->sectionBlock(function (SectionBlock $block) { $block->text('An invoice has been paid.'); }) ->actionsBlock(function (ActionsBlock $block) { $block->button('Acknowledge Invoice') ->primary() ->confirm( 'Acknowledge the payment and send a thank you email?', function (ConfirmObject $dialog) { $dialog->confirm('Yes'); $dialog->deny('No'); } ); }); }

Slack 블록 확인하기

구성 중인 블록을 빠르게 확인하고 싶다면 SlackMessage 인스턴스에서 dd 메서드를 호출하면 됩니다. dd 메서드는 Slack의 Block Kit Builder URL을 생성해 덤프하며, 이 URL을 열면 브라우저에서 페이로드와 알림의 미리보기를 볼 수 있습니다. dd 메서드에 true를 전달하면 원시 페이로드를 덤프합니다:

return (new SlackMessage) ->text('One of your invoices has been paid!') ->headerBlock('Invoice Paid') ->dd();

Slack 알림 라우팅

Slack 알림을 알맞은 Slack 팀과 채널로 보내려면 알림을 받는 모델에 routeNotificationForSlack 메서드를 정의하세요. 이 메서드는 다음 세 가지 값 중 하나를 반환할 수 있습니다:

  • null - 라우팅을 알림 자체에 설정된 채널에 맡깁니다. SlackMessage를 구성할 때 to 메서드를 사용하면 알림 안에서 채널을 지정할 수 있습니다.
  • 알림을 보낼 Slack 채널을 지정하는 문자열. 예: #support-channel
  • SlackRoute 인스턴스. OAuth 토큰과 채널 이름을 지정할 수 있습니다. 예: SlackRoute::make($this->slack_channel, $this->slack_token). 외부 워크스페이스로 알림을 보낼 때는 이 방식을 사용해야 합니다.

예를 들어 routeNotificationForSlack 메서드에서 #support-channel을 반환하면, 애플리케이션의 services.php 설정 파일에 있는 Bot User OAuth 토큰과 연결된 워크스페이스의 #support-channel 채널로 알림이 전송됩니다:

<?php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notification; class User extends Authenticatable { use Notifiable; /** * Slack 채널의 알림 라우팅 정보를 반환합니다. */ public function routeNotificationForSlack(Notification $notification): mixed { return '#support-channel'; } }

외부 Slack 워크스페이스에 알림 보내기

NOTE

외부 Slack 워크스페이스로 알림을 보내려면 먼저 Slack App이 배포되어 있어야 합니다.

애플리케이션 사용자가 소유한 Slack 워크스페이스로 알림을 보내야 하는 경우도 많습니다. 그러려면 먼저 해당 사용자의 Slack OAuth 토큰을 발급받아야 합니다. 다행히 Laravel Socialite에 Slack 드라이버가 포함되어 있어, 애플리케이션 사용자를 Slack으로 손쉽게 인증하고 봇 토큰을 발급받을 수 있습니다.

봇 토큰을 발급받아 애플리케이션의 데이터베이스에 저장했다면 SlackRoute::make 메서드로 알림을 사용자의 워크스페이스로 라우팅할 수 있습니다. 아울러 알림을 어느 채널로 보낼지 사용자가 직접 지정할 수 있는 기능도 애플리케이션에서 제공해야 할 가능성이 큽니다:

<?php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notification; use Illuminate\Notifications\Slack\SlackRoute; class User extends Authenticatable { use Notifiable; /** * Slack 채널의 알림 라우팅 정보를 반환합니다. */ public function routeNotificationForSlack(Notification $notification): mixed { return SlackRoute::make($this->slack_channel, $this->slack_token); } }

알림 다국어 처리

Laravel에서는 HTTP 요청의 현재 로케일과 다른 로케일로 알림을 보낼 수 있으며, 알림이 큐에 들어가더라도 이 로케일을 기억합니다.

이를 위해 Illuminate\Notifications\Notification 클래스는 원하는 언어를 지정하는 locale 메서드를 제공합니다. 애플리케이션은 알림을 평가하는 동안 이 로케일로 전환되었다가, 평가가 끝나면 이전 로케일로 되돌아갑니다:

$user->notify((new InvoicePaid($invoice))->locale('es'));

알림을 받는 대상이 여럿일 때도 Notification 파사드를 통해 로케일을 지정할 수 있습니다:

Notification::locale('es')->send( $users, new InvoicePaid($invoice) );

사용자 선호 로케일

애플리케이션이 사용자마다 선호하는 로케일을 저장해 두는 경우가 있습니다. 알림을 받는 모델에 HasLocalePreference 컨트랙트를 구현하면, Laravel이 알림을 보낼 때 저장된 로케일을 사용하도록 할 수 있습니다:

use Illuminate\Contracts\Translation\HasLocalePreference; class User extends Model implements HasLocalePreference { /** * 사용자가 선호하는 로케일을 반환합니다. */ public function preferredLocale(): string { return $this->locale; } }

이 인터페이스를 구현하면 Laravel이 해당 모델에 알림과 mailable을 보낼 때 선호 로케일을 자동으로 사용합니다. 따라서 이 인터페이스를 사용할 때는 locale 메서드를 호출할 필요가 없습니다:

$user->notify(new InvoicePaid($invoice));

테스트

Notification 파사드의 fake 메서드를 사용하면 알림이 실제로 전송되지 않도록 막을 수 있습니다. 알림 전송은 대개 실제로 테스트하려는 코드와 관련이 없습니다. 대부분의 경우 Laravel이 특정 알림을 보내도록 지시받았는지만 확인하면 충분합니다.

Notification 파사드의 fake 메서드를 호출한 뒤에는 사용자에게 알림을 보내도록 지시되었는지 확인할 수 있고, 알림이 전달받은 데이터까지 검사할 수 있습니다:

Pest

<?php use App\Notifications\OrderShipped; use Illuminate\Support\Facades\Notification; test('orders can be shipped', function () { Notification::fake(); // 주문 배송 처리를 수행합니다... // 알림이 하나도 전송되지 않았는지 확인합니다... Notification::assertNothingSent(); // 지정한 사용자들에게 알림이 전송되었는지 확인합니다... Notification::assertSentTo( [$user], OrderShipped::class ); // 알림이 전송되지 않았는지 확인합니다... Notification::assertNotSentTo( [$user], AnotherNotification::class ); // 알림이 두 번 전송되었는지 확인합니다... Notification::assertSentTimes(WeeklyReminder::class, 2); // 사용자에게 알림이 정확히 한 번 전송되었는지 확인합니다... Notification::assertSentToOnce($user, OrderShipped::class); // 지정한 개수만큼 알림이 전송되었는지 확인합니다... Notification::assertCount(3); });

PHPUnit

<?php namespace Tests\Feature; use App\Notifications\OrderShipped; use Illuminate\Support\Facades\Notification; use Tests\TestCase; class ExampleTest extends TestCase { public function test_orders_can_be_shipped(): void { Notification::fake(); // 주문 배송 처리를 수행합니다... // 알림이 하나도 전송되지 않았는지 확인합니다... Notification::assertNothingSent(); // 지정한 사용자들에게 알림이 전송되었는지 확인합니다... Notification::assertSentTo( [$user], OrderShipped::class ); // 알림이 전송되지 않았는지 확인합니다... Notification::assertNotSentTo( [$user], AnotherNotification::class ); // 알림이 두 번 전송되었는지 확인합니다... Notification::assertSentTimes(WeeklyReminder::class, 2); // 사용자에게 알림이 정확히 한 번 전송되었는지 확인합니다... Notification::assertSentToOnce($user, OrderShipped::class); // 지정한 개수만큼 알림이 전송되었는지 확인합니다... Notification::assertCount(3); } }

assertSentTo나 assertNotSentTo 메서드에 클로저를 전달하면 주어진 "참/거짓 테스트"를 통과하는 알림이 전송되었는지 확인할 수 있습니다. 이 테스트를 통과하는 알림이 하나라도 전송되었다면 단언은 성공합니다:

Notification::assertSentTo( $user, function (OrderShipped $notification, array $channels) use ($order) { return $notification->order->id === $order->id; } );

또는 assertSentTo나 assertNotSentTo의 세 번째 인자로 기대하는 프로퍼티 값의 배열을 전달할 수도 있습니다:

Notification::assertSentTo($user, OrderShipped::class, ['order' => $order]);

지정한 프로퍼티는 모두 일치해야 합니다. 값은 엄격한 동등 비교로 비교하고, Eloquent 모델은 is 메서드로 비교합니다. assertSentOnDemand의 두 번째 인자로도 기대하는 프로퍼티 값의 배열을 전달할 수 있습니다.

온디맨드 알림

테스트하려는 코드가 온디맨드 알림을 보낸다면 assertSentOnDemand 메서드로 온디맨드 알림이 전송되었는지 테스트할 수 있습니다:

Notification::assertSentOnDemand(OrderShipped::class); Notification::assertSentOnDemandOnce(OrderShipped::class);

assertSentOnDemand 메서드의 두 번째 인자로 클로저를 전달하면 온디맨드 알림이 올바른 "라우트" 주소로 전송되었는지 확인할 수 있습니다:

Notification::assertSentOnDemand( OrderShipped::class, function (OrderShipped $notification, array $channels, object $notifiable) use ($user) { return $notifiable->routes['mail'] === $user->email; } );

알림 이벤트

알림 전송 중 이벤트

알림이 전송되려 할 때 알림 시스템은 Illuminate\Notifications\Events\NotificationSending 이벤트를 디스패치합니다. 이 이벤트에는 알림을 받는 "notifiable" 엔티티와 알림 인스턴스 자체가 담겨 있습니다. 애플리케이션에서 이 이벤트에 대한 이벤트 리스너를 만들 수 있습니다:

use Illuminate\Notifications\Events\NotificationSending; class CheckNotificationStatus { /** * 이벤트를 처리합니다. */ public function handle(NotificationSending $event): void { // ... } }

NotificationSending 이벤트의 리스너가 handle 메서드에서 false를 반환하면 알림은 전송되지 않습니다:

/** * 이벤트를 처리합니다. */ public function handle(NotificationSending $event): bool { return false; }

이벤트 리스너 안에서는 이벤트의 notifiable, notification, channel 프로퍼티에 접근해 알림 수신자나 알림 자체에 대한 정보를 얻을 수 있습니다:

/** * 이벤트를 처리합니다. */ public function handle(NotificationSending $event): void { // $event->channel // $event->notifiable // $event->notification }

알림 전송 완료 이벤트

알림이 전송되면 알림 시스템은 Illuminate\Notifications\Events\NotificationSent 이벤트를 디스패치합니다. 이 이벤트에는 알림을 받는 "notifiable" 엔티티와 알림 인스턴스 자체가 담겨 있습니다. 애플리케이션에서 이 이벤트에 대한 이벤트 리스너를 만들 수 있습니다:

use Illuminate\Notifications\Events\NotificationSent; class LogNotification { /** * 이벤트를 처리합니다. */ public function handle(NotificationSent $event): void { // ... } }

이벤트 리스너 안에서는 이벤트의 notifiable, notification, channel, response 프로퍼티에 접근해 알림 수신자나 알림 자체에 대한 정보를 얻을 수 있습니다:

/** * 이벤트를 처리합니다. */ public function handle(NotificationSent $event): void { // $event->channel // $event->notifiable // $event->notification // $event->response }

커스텀 채널

Laravel은 몇 가지 알림 채널을 기본으로 제공하지만, 다른 채널로 알림을 전달하기 위해 드라이버를 직접 작성하고 싶을 때도 있습니다. Laravel에서는 이 작업이 간단합니다. 먼저 send 메서드가 있는 클래스를 정의하세요. 이 메서드는 $notifiable과 $notification, 두 개의 인자를 받아야 합니다.

send 메서드 안에서는 알림의 메서드를 호출해 채널이 이해할 수 있는 메시지 객체를 가져온 다음, 원하는 방식으로 $notifiable 인스턴스에 알림을 보내면 됩니다:

<?php namespace App\Notifications; use Illuminate\Notifications\Notification; class VoiceChannel { /** * 주어진 알림을 전송합니다. */ public function send(object $notifiable, Notification $notification): void { $message = $notification->toVoice($notifiable); // $notifiable 인스턴스에 알림을 전송합니다... } }

알림 채널 클래스를 정의했다면, 어떤 알림에서든 via 메서드에서 이 클래스 이름을 반환할 수 있습니다. 이 예시에서 알림의 toVoice 메서드는 음성 메시지를 표현하는 객체라면 무엇이든 반환할 수 있습니다. 예를 들어 이런 메시지를 표현하는 VoiceMessage 클래스를 직접 정의할 수 있습니다:

<?php namespace App\Notifications; use App\Notifications\Messages\VoiceMessage; use App\Notifications\VoiceChannel; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; class InvoicePaid extends Notification { use Queueable; /** * 알림 채널을 반환합니다. */ public function via(object $notifiable): string { return VoiceChannel::class; } /** * 알림의 음성 표현을 반환합니다. */ public function toVoice(object $notifiable): VoiceMessage { // ... } }

이 문서는 Laravel 공식 문서(MIT)를 한국 개발자를 위해 번역·재구성한 것입니다.

번역일: 2026년 11월 18일