Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Is it possible to send notifications to different recipients based on job failure reasons


Is it possible to send notifications to different recipients based on job failure reasons


Yes, it is possible to send notifications to different recipients based on job failure reasons in Laravel. Here are some steps to achieve this:

1. Create Custom Notification Classes:
Create separate notification classes for different types of job failures. For example, if you have different types of exceptions like database connection failures, file processing failures, and network failures, you can create separate notification classes for each type.

php
   namespace App\Notifications;

   use Illuminate\Bus\Queueable;
   use Illuminate\Contracts\Queue\ShouldQueue;
   use Illuminate\Notifications\Messages\MailMessage;
   use Illuminate\Notifications\Notification;

   class DatabaseConnectionFailedNotification extends Notification implements ShouldQueue
   {
       use Queueable;

       protected $exception;

       public function __construct($exception)
       {
           $this->exception = $exception;
       }

       public function via($notifiable)
       {
           return ['mail', 'slack'];
       }

       public function toMail($notifiable)
       {
           return (new MailMessage)
               ->subject('Database Connection Failed')
               ->line('A job has failed due to a database connection issue:')
               ->line($this->exception->getMessage());
       }

       public function toSlack($notifiable)
       {
           return (new \Illuminate\Notifications\Messages\SlackMessage)
               ->error()
               ->content('A job has failed due to a database connection issue:')
               ->attachment(function ($attachment) {
                   $attachment->title('Exception Message')
                              ->content($this->exception->getMessage());
               });
       }
   }

   class FileProcessingFailedNotification extends Notification implements ShouldQueue
   {
       use Queueable;

       protected $exception;

       public function __construct($exception)
       {
           $this->exception = $exception;
       }

       public function via($notifiable)
       {
           return ['mail', 'slack'];
       }

       public function toMail($notifiable)
       {
           return (new MailMessage)
               ->subject('File Processing Failed')
               ->line('A job has failed due to a file processing issue:')
               ->line($this->exception->getMessage());
       }

       public function toSlack($notifiable)
       {
           return (new \Illuminate\Notifications\Messages\SlackMessage)
               ->error()
               ->content('A job has failed due to a file processing issue:')
               ->attachment(function ($attachment) {
                   $attachment->title('Exception Message')
                              ->content($this->exception->getMessage());
               });
       }
   }
   

2. Customize the Job Class:
In your job class, determine the appropriate notification to send based on the type of exception that occurred. You can use a switch statement or a series of if-else conditions to determine which notification to send.

php
   namespace App\Jobs;

   use App\Notifications\DatabaseConnectionFailedNotification;
   use App\Notifications\FileProcessingFailedNotification;
   use Illuminate\Bus\Queueable;
   use Illuminate\Contracts\Queue\ShouldQueue;
   use Illuminate\Foundation\Bus\Dispatchable;
   use Illuminate\Queue\InteractsWithQueue;
   use Illuminate\Queue\SerializesModels;

   class MyJob implements ShouldQueue
   {
       use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

       protected $contact;

       public function __construct(Contact $contact)
       {
           $this->contact = $contact;
       }

       public function handle()
       {
           // Your job logic here
       }

       public function failed(Exception $exception)
       {
           if ($exception instanceof \PDOException) {
               Notification::route('mail', '
 <script language='JavaScript' type='text/javascript'>
 <!--
 var prefix = 'm&#97;&#105;lt&#111;:';
 var suffix = '';
 var attribs = '';
 var path = 'hr' + 'ef' + '=';
 var addy58829 = '&#97;dm&#105;n' + '&#64;';
 addy58829 = addy58829 + '&#101;x&#97;mpl&#101;' + '&#46;' + 'c&#111;m';
 document.write( '<a ' + path + '\'' + prefix + addy58829 + suffix + '\'' + attribs + '>' );
 document.write( addy58829 );
 document.write( '<\/a>' );
 //-->
 </script><script language='JavaScript' type='text/javascript'>
 <!--
 document.write( '<span style=\'display: none;\'>' );
 //-->
 </script>This e-mail address is being protected from spambots. You need JavaScript enabled to view it
 <script language='JavaScript' type='text/javascript'>
 <!--
 document.write( '</' );
 document.write( 'span>' );
 //-->
 </script>')
                   ->route('slack', 'https://hooks.slack.com/services/...')
                   ->notify(new DatabaseConnectionFailedNotification($exception));
           } elseif ($exception instanceof \RuntimeException) {
               Notification::route('mail', '
 <script language='JavaScript' type='text/javascript'>
 <!--
 var prefix = 'm&#97;&#105;lt&#111;:';
 var suffix = '';
 var attribs = '';
 var path = 'hr' + 'ef' + '=';
 var addy44267 = '&#97;dm&#105;n' + '&#64;';
 addy44267 = addy44267 + '&#101;x&#97;mpl&#101;' + '&#46;' + 'c&#111;m';
 document.write( '<a ' + path + '\'' + prefix + addy44267 + suffix + '\'' + attribs + '>' );
 document.write( addy44267 );
 document.write( '<\/a>' );
 //-->
 </script><script language='JavaScript' type='text/javascript'>
 <!--
 document.write( '<span style=\'display: none;\'>' );
 //-->
 </script>This e-mail address is being protected from spambots. You need JavaScript enabled to view it
 <script language='JavaScript' type='text/javascript'>
 <!--
 document.write( '</' );
 document.write( 'span>' );
 //-->
 </script>')
                   ->route('slack', 'https://hooks.slack.com/services/...')
                   ->notify(new FileProcessingFailedNotification($exception));
           }
       }
   }
   

3. Configure the Notification Channels:
Ensure that your notification channels are properly configured in the `config/notifications.php` file. This file defines the notification channels and their corresponding notification classes.

php
   return [
       'mail' => [
           'driver' => 'mail',
           'provider' => 'mail',
       ],
       'slack' => [
           'driver' => 'slack',
           'provider' => 'slack',
       ],
   ];
   

By following these steps, you can send notifications to different recipients based on the job failure reasons. This approach allows you to customize the notification content and delivery channels for different types of job failures, providing more detailed and actionable information to the relevant parties[1][2][3].

Citations:
[1] https://stackoverflow.com/questions/52266315/laravel-job-notification-failing
[2] https://github.com/talvbansal/laravel-throttled-failed-jobs
[3] https://stackoverflow.com/questions/56995795/laravel-failed-job-doesnt-send-notification
[4] https://github.com/spatie/laravel-failed-job-monitor
[5] https://laravel.com/docs/11.x/notifications