Atef95
6 months ago

Laravel & Pusher instruction

Posted 6 months ago by Atef95

Hey guys I'm new to laravel & pusher combinaison ,I would like to know how can I automatically get my data from pusher when I fire an event in laravel

I'm using react js in front end

here I send an event when I add a new post

  $post=Post::create([
            'title'=>$request->input('title'),
           'description'=>$request->input('description'),
            'user_id' =>$request->input('userId') 
        ]);


        $text="New Post has been added !";
        event(new NewPost($text));



this is NewPost event

<?php

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

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

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('my-channel');
    }
}



This is my code in react to render the data

  componentDidMount() {
  
    const pusher = new Pusher('23525de46fdea6e17af3', {
      cluster: 'eu',
      encrypted: true
    });
    const channel = pusher.subscribe('my-channel');
    channel.bind('NewPost', data => {
      alert(JSON.stringify(data.text))
  
      this.setState({ notifications: JSON.stringify(data.text)});
    });

  }


I can see the data in pusher dashboard succesfuly , but this data doesn't automatically show up in my page only when I hit " send event" button ...

how can I do it automatically after submitting the post?

Please sign in or create an account to participate in this conversation.