imkenee's avatar

Laravel Notifications - Queue ONLY on toMail method?

I've set up Laravel Notifications and so far so good. My set up is that i'm sending two notifications: "mail" and "database". I plan on having the database notification so that I can display the notification somewhere and allow the user to clear it.

The problem is, when I queue the entire Noitification class, as expected, everything is queued... so this means that even database notifications are queued as well. I would like only the "mail" portion to be queued while the database portion is instantly stored to the database. Is this possible?

Here is the class so far.

<?php

namespace App\Notifications;

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

class ViewedDocument extends Notification implements ShouldQueue
{
    use Queueable;

    protected $document;


    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(Document $document)
    {
        $this->document = $document;
    }

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

    /**
     * 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!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            'document_id' => $this->document->id,
            'document_title' => $this->document->title
        ];
    }
}

... And im calling it in a controller somewhere ...

// notification
Notification::send(User::find($document->created_by['user_id']), new ViewedDocument($document));

Thanks

0 likes
2 replies
m7vm7v's avatar

You could separate the logic in two notifications - one for the database and one for the mail. After that you do not need to use the Notification facade but fire an event that will trigger both the notifications. Hope that makes sense. After all then you can make the database notification to be NOT Queueable and then the mail notification can be Queueable.

imkenee's avatar

Hmmm, okay this makes sense, i will look into this. thanks

Please or to participate in this conversation.