【问题标题】:Argument must be instance of message in laravel broadcast参数必须是 laravel 广播中的消息实例
【发布时间】:2018-05-01 16:16:21
【问题描述】:

当我设置广播时,我收到了这个错误:

传递给 App\Events\MessagePosted::__construct() 的参数 1 必须是 App\Events\Message 的一个实例,给出 App\Message 的实例, 在 /var/www/epg/app/Http/Controllers/MessageController.php 上调用 第 25 行 /var/www/epg/app/Events/MessagePosted.php#37

我从我的控制器触发这样的事件

broadcast(new MessagePosted($message, $user))->toOthers();

它应该向该事件广播消息和用户

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Message;
use App\Events\MessagePosted;

class MessageController extends Controller
{
    public function store(Request $request) 
    {
        $user = Auth::user();

        // Store the new message
        $message = $user->messages()->create([
            'message' => $request->get('message')
        ]);

        // Announce that a new message has been posted
        broadcast(new MessagePosted($message, $user))->toOthers();

        return ['status' => 'OK'];
    }
}

我不明白发生了什么,因为我看到人们说检查你的导入,但我在控制器中导入了正确的类。

【问题讨论】:

  • 你能发布你的MessagePosted文件吗?

标签: php laravel laravel-5


【解决方案1】:

确保您的 MessagePosted 文件与此类似

<?php

namespace App\Events;

use App\User; //your model
use App\Message; //your model
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;

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

    public $message;

    public $user;

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

    public function broadcastOn()
    {
        return new PrivateChannel('channel-name'); // your channel name
    }
}

【讨论】:

    【解决方案2】:

    您将App\Message 传递给MessagePosted 构造函数。该错误表明您的MessagePosted 正在接受App\Events\Message 而不是App\Message。当您忘记MessagePosted 中的use App\Message 时往往会发生这种情况,因此它使用MessagePosted 的命名空间,即App\Events 用于Message,从而产生App\Events\Message。

    简而言之,use App\Message 在您的 MessagePosted 类中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-30
      • 2021-08-16
      • 2020-12-06
      • 2020-09-13
      • 2022-06-26
      • 2018-03-12
      • 2020-11-23
      • 1970-01-01
      相关资源
      最近更新 更多