Laravel。如何获取数据库通知的ID?

问题描述 投票:2回答:1

我使用数据库通知,在通知代码中,我有方法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的前端(所以我可以以某种方式将其标识为已读)。如何获得?

P.S。而且,数据库通知可能是可排队的,所以...看来我无法获取ID ...P.P.S另外,我需要包含["id" => "id of just added corresponding database notification"]的广播消息。

laravel laravel-notification
1个回答
1
投票
<?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

P.S。我想提请注意一个事实。当我发布此问题时,我知道$ this-> id,但无法使其正常工作。原因是:当我从顶层更深入地了解目标代码时,我对代码进行了更改,但它们并没有适用。原因是队列。您需要重新启动laravel worker以应用设置,因为Laravel缓存逻辑,或者您需要临时删除这些设置:实现ShouldQueue并使用Queueable。

© www.soinside.com 2019 - 2024. All rights reserved.