首页 > 解决方案 > 拉拉维尔。如何获取数据库通知的ID?

问题描述

我使用数据库通知,在通知代码中我有方法toDatabase

public function toDatabase($notifiable)
    {
        $user = \App\SomeUsers::where('id', $notifiable->id)->first();
        return [
             'message' => $message,
        ];
    }

它返回正在发送到via当前通知方法中提到的数据库通道的数据数组:

public function via($notifiable)

    {
        return ['database'];
    }

一切都像往常一样,但是......问题是我需要在当前通知文件中的数据库中通知 id,以便我可以将消息(来自当前通知文件)广播到包含 db 中通知 id 的前端(所以我可以以某种方式识别它以标记为已读)。如何得到它?

PS 此外,数据库通知可能是可排队的,所以...似乎我无法获取 id... PPS 另一个词我需要包含的广播消息["id" => "id of just added corresponding database notification"]

标签: laravellaravel-notification

解决方案


<?php

namespace App\Notifications;

use App\Channels\SocketChannel;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Redis;

class MyCustomNotification extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */


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

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

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {

    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        info("This is the current notification ID, it's generated right here before inserting to database");
        info($this->id);
        return [

            'id'     =>  **$this->id**,
            'message' => 'Notification message',

        ];
    }


} 

$this->id解决了这个问题。

https://laracasts.com/discuss/channels/laravel/get-database-notification-id-in-push-notification

PS我想提请注意一个事实。当我发布这个问题时,我知道$this->id,但我无法让它发挥作用。原因是:当我从顶层深入研究目标代码时,我对代码进行了更改,但它们并不适用。原因是排队。您需要重新启动 laravel worker 以将设置应用为 Laravel 缓存逻辑,或者您需要暂时删除这些设置:实现 ShouldQueue 并使用 Queueable。


推荐阅读