【问题标题】:How to Make Realtime Notifications in Laravel Sanctum (SPA) - Private Channel Broadcasting?如何在 Laravel Sanctum (SPA) 中进行实时通知 - 私人频道广播?
【发布时间】:2021-06-23 16:37:15
【问题描述】:

我在前端和后端使用 Laravel -v7.x 和 Vue CLI 两个不同的文件夹。并使用 Laravel Sanctum (SPA) 身份验证。我想在后端发生某些事件时创建实时通知。我已经成功配置了 Websockets 和公共广播工作正常。但是当我尝试使用 PrivateChannel 时,后端 WebSockets 可以在我看到的 WebSockets 面板上运行事件,但无法在控制台上获得响应。你能帮我么?下面我分享我的代码。

Vue CLI

#main.js


<script>
import Request from "./apis/Request"
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.VUE_APP_WEBSOCKETS_KEY,
    wsHost: process.env.VUE_APP_WEBSOCKETS_SERVER,
    encrypted: true,
    cluster: 'ap1',
    wsPort: 6001,
    forceTLS: false,
    disableStats: true,
    authorizer: (channel, options) => {
        console.log("OPTIONS>>", options);
        return {
            authorize: (socketId, callback) => {
                Request.POST_REQ('/broadcasting/auth', {
                    socket_id: socketId,
                    channel_name: channel.name
                })
                .then(response => {
                    callback(false, response.data);
                    console.log("RESPONSE>>", response);
                })
                .catch(error => {
                    callback(true, error);
                });
            }
        };
    },
})
</script>

#App.vue


<script>
import { mapGetters } from "vuex";
export default {
    computed: {
    ...mapGetters(["user"])
  },
    async mounted() {
        await window.Echo.private(`hello.user.${this.user.id}`).listen(
      "Hello",
      () => {
        console.log("OK");
      }
    );
    },
}
</script>

#vue 环境

#.env

VUE_APP_WEBSOCKETS_KEY = local
VUE_APP_WEBSOCKETS_SERVER = localhost

#Laravel

#Hello 事件

#Hello.php


<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

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

    public function __construct()
    {
        //
    }

    public function broadcastWith()
    {
        return [
            'hello' => 'Hello world'
        ];
    }

    public function broadcastOn()
    {
        return new PrivateChannel('hello.user.1');
    }
}

#BroadcastServiceProvider.php


<?php

namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;

class BroadcastServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Broadcast::routes();
        Broadcast::routes(["middleware" => ["auth:api"]]);

        require base_path('routes/channels.php');
    }
}

#channels.php


<?php

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('hello.user.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

#laravel 环境

#.env

PUSHER_APP_ID=local
PUSHER_APP_KEY=local
PUSHER_APP_SECRET=local
PUSHER_APP_CLUSTER=ap1

#broadcasting.php


<?php

return [

'default' => env('BROADCAST_DRIVER', 'pusher'),

'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'useTLS' => true,
                'encrypted' => true,
                'host' => 'localhost',
                'port' => 6001,
                'scheme' => 'http'
            ],
        ],
    ],
];

#我使用 tinker 运行事件

php artisan tinker

event(new App\Events\Hello())

【问题讨论】:

    标签: laravel vue.js


    【解决方案1】:

    您应该将Broadcast::routes 方法调用放在您的routes/api.php 文件中,或者更改您现有的BroadcastServiceProvider::boot() 方法以使用sanctum 作为身份验证驱动程序:

    Broadcast::routes(['middleware' => ['auth:sanctum']]);
    

    【讨论】:

      猜你喜欢
      • 2018-02-23
      • 2018-03-03
      • 2021-11-15
      • 2021-07-15
      • 2020-08-25
      • 2021-06-01
      • 2023-03-17
      • 2019-08-28
      • 2020-03-24
      相关资源
      最近更新 更多