Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 3 commits into from
Oct 28, 2022

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