Search code examples
phplaraveleventsbroadcastpusher

Laravel event error, to few arguments to function


I am trying to broadcast an event without success. I can't find what the issue is and i am out of ideas. The error i am getting is.

"Too few arguments to function App\Events\ConversationUpdate::__construct(),
1 passed in /app/Events/ConversationUpdate.php on line 36 and exactly 2 expected"

What i am trying to do is when a message is created, broadcast an event to the chat and update the chat with the new message in realtime.

here is my code:

Controller:

public function newConversationMessage(Thread $conversation, Request $request)
    {
        $user = Auth::user();
        $message = Message::create([
            'thread_id' => $conversation->id,
            'user_id' => $user->id,
            'body' => $request->body,
        ]);
        $message->user; 
        broadcast(new ConversationUpdate($conversation->id, $message));    
        return $message;
    }

Event:

namespace App\Events;

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 ConversationUpdate implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $conversationId;


    public $message;


    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($conversationId, $message)
    {
        $this->conversationId = $conversationId;
        $this->message = $message;
    }

    public function broadcastOn()
    {
        return new ConversationUpdate('conversation-'.$this->conversationId.'-updated');
    }
}

Solution

  • on function broadcastOn() you should return something like this

    return new PrivateChannel('conversation-'.$this->conversationId.'-updated');
    

    and not another instance of the the same class you are in (the error depends infact to the single argument you are passing in the constructor)