In a previous tip, I shared some ideas on handling conditional notifications.
Shortly after posting, Newton shared another approach which is even better for this exact use case.
Inside the notification class, you can define a shouldSend
method to centralize that conditional logic.
Using this with my previous example, it would look like this:
public function shouldSend(object $notifiable, string $channel): bool
{
// add whatever logic you want to determine if the notification should be sent
// return true if it should be sent, false otherwise
}
Now I don't need to emit an event and wire up a listener, and I also don't spread this conditional logic multiple places in my app.
And this has been there since Laravel 8!
Here to help,
Joel
P.S. Testing not only helps you catch bugs, but it can help you design better structure in your code. If you feel unsure on how to introduce testing to your Laravel app, we can help!