Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: How to limit retries on queued notifications

Tags:

laravel

From the Laravel manual, I understand that I can limit the number of times a queued job is retried using either the command line (when starting the queue), or by setting the $tries property on the job class itself. https://laravel.com/docs/5.6/queues#max-job-attempts-and-timeout

I want to set the maximum number of retries within the job itself, not using the command line, however the job is actually a custom class that inherits from Illuminate\Notifications\Notification, not an App\Job. In this case, is it possible to limit the number of tries?

I tried setting the $tries property in my customer notification, but it had no effect. I am using a custom channel as well, but setting the $tries there had no effect either.

like image 294
DatsunBing Avatar asked Jan 27 '23 21:01

DatsunBing


2 Answers

In your notification file add the Queueable trait. It's this trait that gives you the possibility to alter the number of tries.

use Illuminate\Bus\Queueable;

class MyNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public $tries = 3;
like image 141
Ole Haugset Avatar answered Feb 05 '23 17:02

Ole Haugset


As of Laravel 5.7+, you can easily limit maximum tries by adding $tries property to the Queueable Notification.

Usage example from the PR author (laravel/framework GitHub PR 26493#):

<?php

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

class TestNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public $tries = 3; // Max tries

    public $timeout = 15; // Timeout seconds

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }
}
like image 44
MohannadNaj Avatar answered Feb 05 '23 17:02

MohannadNaj