redis - 拉维尔 5.4 : Listening For Notifications doesn't work with me

标签 redis notifications laravel-5.4 broadcasting laravel-echo

我无法让这段代码在 ( laravel5.4/notifications#broadcast-notifications ) 之后工作:

Echo.private('App.User.' + userId)
    .notification((notification) => {
        console.log(notification.type);
    });

这是我的代码:
应用程序.js:

require('./bootstrap')

import Echo from 'laravel-echo'

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: 'http://127.0.0.1:6001'
})


window.Echo.private('App.User.' + window.Laravel.user.id)               
.notification((notification) => {
    console.log(notification);
    // toastr.info(' has created new ticket !! ', 'info');        
});

创建TeckitNotify:

<?php

namespace App\Notifications\Ticket;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;

use App\Models\Ticket\Ticket;



class CreateTicketNotify extends Notification  implements ShouldQueue, ShouldBroadcast
{
    use Queueable, SerializesModels;


    public $ticket;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($ticket)
    {
        $this->ticket = $ticket;
    }

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

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        $url = url('/ticket/'.$this->ticket->id);
        return (new MailMessage)
                    ->subject('New Ticket Created')
                    ->greeting('Hello, '.$this->ticket->user->lastname.' !')
                    ->line('A new ticket has been created')
                    ->action('View Ticket', $url)
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
       return [
            'ticket_id' => $this->ticket->id,                     
        ];
    }

    // public function toDatabase($notifiable)
    // {
    //     return [

    //     ];
    // }

    public function toBroadcast($notifiable)
    {

        return new BroadcastMessage([
            'ticket' => $this->ticket
        ]);
    }


}

路线:

Route::get('/test', function() {    
    $user = \App\User::find(2);

    $user->notify(new \App\Notifications\Ticket\CreateTicketNotify('Hello There'));
    return "Event has been sent!";
});

channel 路线:

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

Broadcast::channel('ticket.{id}', function ($user, $id) {
    // $ticket = App\Models\Ticket\Ticket::find($ticketID);
    // return $ticket->category->users->has(Auth::id());
    // if(Auth::id()==1)        
    // if($id == 0)
    //  return false;
    // else
        return true;
    $ticket = App\Models\Ticket\Ticket::find($id);

    if (in_array(Auth::id(), $ticket->category->users->pluck('id')->toArray()) )
        return true;
    else
        return false;

    // return (int) $user->id !== (int) App\Models\Ticket\Ticket::find($ticketID)->user->id;
    // else
    //  return false;
});

用户模型:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\HasMedia\Interfaces\HasMedia;
use Auth;

class User extends Authenticatable implements HasMedia
{
    use Notifiable, HasRoles, HasMediaTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'lastname', 'firstname', 'email', 'password', 'active',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];




    public function tickets()
    {
        return $this->hasMany('App\Models\Ticket\Ticket');
    } 

    public function receivesBroadcastNotificationsOn()
    {
        return 'users.'.$this->id;
    }
}

创建票证事件

<?php

namespace App\Events;

use App\Events\Event;

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


use App\Models\Ticket\Ticket;

class CreateTicketEvent implements ShouldQueue, ShouldBroadcast 
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $ticket;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Ticket $ticket)
    {
        $this->ticket = $ticket;
        //  $this->ticket = array(
        //     'power'=> '10'
        // );
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {        
        return new PrivateChannel('ticket.' . $this->ticket->id);
        // return ['ticket'];
    }

    // public function broadcastWith()
    // {
    //     return array('subject' => $this->ticket->subject);
    // }
}

我的终端: enter image description here 控制台输出:

[03:31:28] - 8bnJMpO-fFVs9LSyAAAE joined channel: ticket
[03:31:28] - 8bnJMpO-fFVs9LSyAAAE authenticated for: private-App.User.2
[03:31:28] - 8bnJMpO-fFVs9LSyAAAE joined channel: private-App.User.2
Channel: private-users.2
Event: Illuminate\Notifications\Events\BroadcastNotificationCreated
CHANNEL private-users.2

正如你所看到的,用户 2 已经加入了 channel 并且通知已经被触发但是使用这个没有显示任何东西:

window.Echo.private('App.User.' + window.Laravel.user.id)               
    .notification((notification) => {
        console.log(notification);
        // toastr.info(' has created new ticket !! ', 'info');        
    });

请帮帮我....

最佳答案

我认为这是因为您在用户模型中使用 receivesBroadcastNotificationsOn() 自定义了通知 channel ,并且您正在 App.User.* 上监听事件而不是 user.*

因此只需从 User 模型中删除 receivesBroadcastNotificationsOn() 并再次检查。

希望对你有帮助

关于redis - 拉维尔 5.4 : Listening For Notifications doesn't work with me,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45293237/

相关文章:

elasticsearch - ES 的 Jedis 'front end'

json - 如何确保我的 View 在数据库操作后呈现?

connection - redis客户端是否使用长连接

android - 显示来自 BroadcastReceiver 的状态栏通知

android - 如何在android中通过代码更改通知声音?

laravel - Laravel 5.4 上的搜索引擎优化

java - 将 ShardedJedis 与 RedisTemplate 一起使用

php - Laravel 5.4 中的数据未从 Controller 存储到数据库中

php - 拉维尔 |询问某些操作的密码

javascript - 服务器发送事件 : Not working