首页 > 解决方案 > 带有 socket-io 的 Laravel 事件 [接收通知]

问题描述

第一次尝试,laravelsocket-io正在尝试向管理员发送非常简单的通知。到目前为止,我的事件正在触发,但在接收事件通知方面我需要帮助

逻辑

这是非常基本的,因为我想了解这个过程。

  1. 用户打开页面Add Product
  2. user X管理员收到页面中的通知App Product

至今

到目前为止,我可以触发事件并获取用户数据(Add Product页面中的用户)

需要帮助

我需要帮助来了解管理员接收通知的方式。

代码

组件脚本

created() {
  let user = JSON.parse(localStorage.getItem("user"))
  this.listenForBroadcast(user);
},
methods: {
  listenForBroadcast(user) {
    Echo.join('userInAddProduct')
    .here((Loggeduser) => {
      console.log('My user data', Loggeduser);
    });
  }
}

上面代码的结果

My user data [{…}]
  0:
    id: 1
    name: "Test User"
    photo: "User-1588137335.png"
    __ob__: Observer {value: {…}, dep: Dep, vmCount: 0}
    get id: ƒ reactiveGetter()
    set id: ƒ reactiveSetter(newVal)
    get name: ƒ reactiveGetter()
    set name: ƒ reactiveSetter(newVal)
    get photo: ƒ reactiveGetter()
    set photo: ƒ reactiveSetter(newVal)
    __proto__: Object
    length: 1
    __proto__: Array(0)

渠道路线

Broadcast::channel('userInAddProduct', function ($user) {
    return [
        'id' => $user->id,
        'photo' => $user->photo,
        'name' => $user->name
    ];
});

MessagePushed(事件文件)

class MessagePushed implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;

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

    public function broadcastOn()
    {
        return new PresenceChannel('userInAddProduct');
    }
}

问题

如何接收有关此事件触发的通知?我想通知user x页面中的管理员用户Add Product

更新

自从我发布了这个问题以来,我做了一些更改,这是我最新的代码 + 问题。

bootstrap.js

window.io = require('socket.io-client');

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001',
    auth: { // added authentication token (because all my events are private)
        headers: {
            Authorization: localStorage.getItem('access_token'),
        },
    },
});

Add.vue (add product component where event has to be fired)

listenForBroadcast(user) {
    let ui = JSON.parse(localStorage.getItem("user"))
    Echo.join('userInAddProduct')
    .here((users) => {
        console.log('My user data', users)
    })
    .joining((user) => {
        this.$notify({
            title: '',
            message: user + 'joining',
            offset: 100,
            type: 'success'
        });
    })
    .leaving((user) => {
        this.$notify({
            title: '',
            message: user + 'is leaving new product',
            offset: 100,
            type: 'warning'
        });
    })
    .whisper('typing', (e) => {
        this.$notify({
            title: '',
            message: ui.username + 'is adding new product',
            offset: 100,
            type: 'success'
        })
    })
    .listenForWhisper('typing', (e) => {
        console.log(e)
        this.$notify({
            title: '',
            message: ui.username + 'is entered add new product page.',
            offset: 100,
            type: 'success'
        });
    })
    .notification((notification) => {
        console.log('noitication listener: ', notification.type);
    });
},

然后我制作了 4 个文件来处理事件:

Event file

class MessagePushed extends Event implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;
    public $product;

    public function __construct(User $user, Product $product)
    {
        $this->user = $user;
        $this->product = $product;
    }

    public function broadcastOn()
    {
        return new PresenceChannel('userInAddProduct');
    }
}

Listener file

class ThingToDoAfterEventWasFired implements ShouldQueue
{
    public function handle(MessagePushed $event)
    {
        //Log testing purpose only
        $user = $event->user->username;
        $product = $event->product->name;

        // Real data that should be broadcasts
        $user2 = $event->user;
        $product2 = $event->product;

        // inform all admins and authorized staffs about new product
        $admins = User::role(['admin', 'staff'])->get();
        foreach($admins as $admin) {
            $admin->notify(new UserAddProduct($user2, $product2));
        }

        Log::info("Product $product was Created, by worker: $user");
    }
}

Notification

class UserAddProduct extends Notification implements ShouldQueue
{
    use Queueable;

    protected $product;
    protected $user;

    public function __construct(User $user, Product $product)
    {
        $this->product = $product;
        $this->user = $user;
    }

    public function via($notifiable)
    {
        return ['database', 'broadcast'];
    }

    public function toDatabase($notifiable)
    {
        return [
            'user_id' => $this->user->id,
            'user_username' => $this->user->username,
            'product_id' => $this->product->id,
            'product_name' => $this->product->name,
        ];
    }

    public function toArray($notifiable)
    {
        return [
            'id' => $this->id,
            'read_at' => null,
            'data' => [
                'user_id' => $this->user->id,
                'user_username' => $this->user->username,
                'product_id' => $this->product->id,
                'product_name' => $this->product->name,
            ],
        ];
    }
}

Observer

public function created(Product $product)
{
    $user = Auth::user();
    event(new MessagePushed($user, $product));
}

问题

  1. 如何在整个应用程序中触发事件后立即返回实时通知?目前因为我的代码被放置在add.vue component admins get notify IF they are in same page only :/
  2. 如何获得多个事件的通知?假设我有另一个页面操作我希望管理员在整个应用程序中都得到event, listener, observer通知。product eventother event

谢谢

标签: phplaravelsocket.io

解决方案


我最近写了一篇文章如何将 Laravel WebSockets 用于 NuxtJs 通知,其中我详细描述了包括 Laravel WebSockets 的事件设置。希望对你有帮助。


推荐阅读