Skip to content

Instantly share code, notes, and snippets.

@jasonlbeggs
Created March 6, 2021 00:30
Show Gist options
  • Save jasonlbeggs/d76246bd094d1a7ac21c035a78853e2f to your computer and use it in GitHub Desktop.
Save jasonlbeggs/d76246bd094d1a7ac21c035a78853e2f to your computer and use it in GitHub Desktop.

Notification when() method

When sending notifications with Laravel, there's a when() method on each message type that can be used to optionally add lines or actions when some value is true. Very similar concept the the when method on the QueryBuilder and Collections.

Query Builder Example

Team::when(request()->has('filters.name'), function ($query) {
    $q->where('name', request('filters.name'));
})->get();

Notification Example

<?php

// ...

class ExampleNotification extends Notification
{
    // ...
    
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting('Hello world')
                    ->when($this->team->isOnFreePlan(), function ($message) {
                        $message->action('Upgrade', );
                    });
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment