Skip to content

[9.x] Add ability to set middleware based on notifiable instance and channel#44767

Merged
taylorotwell merged 3 commits intolaravel:9.xfrom
AndrewMonty:notification-middleware-context
Oct 28, 2022
Merged

[9.x] Add ability to set middleware based on notifiable instance and channel#44767
taylorotwell merged 3 commits intolaravel:9.xfrom
AndrewMonty:notification-middleware-context

Conversation

@AndrewMonty
Copy link
Contributor

Discussed in #44766

I want to apply middleware to my queueable notifications, but only for specific channels and/or users. For example; no middleware for database notifications, but apply a rate limiter to email and sms notifications - unless the notifiable is an admin.

My suggestion is to pass $notifiable and $channel to the middleware() method on queuable notifications, similar to how withDelay works.

Now I can change my middleware stack depending on the notifiable and channel of each job instance.

class ImportantNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function via($notifiable)
    {
        return [
            'email',
            'database',
            'broadcast',
        ];
    }

    public function middleware($notifiable, $channel)
    {
        if ($notifiable instance of User && $notifiable->isAdmin()) {
            return [];
        }

        if ($channel == 'email') {
            return [new RateLimited('mailgun')];
        }

        return [];
    }

    ...
}
Notification::send($users, new ImportantNotification);

@taylorotwell taylorotwell merged commit 5459402 into laravel:9.x Oct 28, 2022
@GrahamCampbell GrahamCampbell changed the title added ability to set middleware based on notifiable instance and channel [9.x] Add ability to set middleware based on notifiable instance and channel Nov 6, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants