参数必须是laravel广播中的消息实例

时间:2018-05-01 16:16:22

标签: php laravel laravel-5

当我设置广播时,我收到此错误:

  

传递给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'];
    }
}

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

2 个答案:

答案 0 :(得分:0)

确保您的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
    }
}

答案 1 :(得分:0)

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

简而言之,Message类中的App\Events\Message