A
A
ADamCarraway2022-01-03 14:32:17
Laravel
ADamCarraway, 2022-01-03 14:32:17

Have I implemented bulk notifications correctly?

When a user adds a post, all subscribers receive notifications.
There is a listener that fires when a post is created adds work to the queue

class AddPostNotify
{
    public function handle(PostCreated $event)
    {
        dispatch(new AddPostNotificationJob($event->post));
    }
}

This work adds notifications to the queue
public function handle()
{
Subs::query()->each(function (Notification $notification) {
                $notification->user->notify(new AddPostNotification($this->post));
            });
}

The notification itself
class AddPostNotification extends Notification implements ShouldQueue
{
    use Queueable;

    private Post $post;

    public function __construct(Post $post)
    {
        $this->post = $post;
    }

    public function via($notifiable)
    {
        $this->onQueue('notification');

        return $notifiable->isNotificationEnabled(self::class) ? ['broadcast', 'database'] : [];
    }

    public function toArray($notifiable)
    {
        return [
            //
        ];
    }

    public function toDatabase($notifiable)
    {
        return new BroadcastMessage([
            'post' => $this->post,
        ]);
    }

    public function toBroadcast($notifiable)
    {
        return new BroadcastMessage([
            'data' => [
                'post' => $this->post,
            ],
        ]);
    }
}


Also, according to this principle, I implemented notifications about adding comments.
Is the logic correct? Or can something better be done?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex Wells, 2022-01-04
@Alex_Wells

It's ok if there aren't too many subs. Over time, you will run into a job time limit due to ->each (). Then you will run into the number of notifications that you write to the database for each sub. Even later - in sending a broadcast through a personal channel to each user, and not all at once to one.
Solve problems as you go, there is no point in trying to solve them in advance.

J
jazzus, 2022-01-05
@jazzus

To send to a group of subscribers, you need to use the facade https://laravel.com/docs/8.x/notifications#using-t...
The check that in isNotificationEnabled can be done in the where query before creating notifications.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question