<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ankit Patel</title>
    <description>The latest articles on DEV Community by Ankit Patel (@ankitmpatel).</description>
    <link>https://dev.to/ankitmpatel</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F32222%2F21fd45ea-5489-4f0e-9af2-91285f1553ff.png</url>
      <title>DEV Community: Ankit Patel</title>
      <link>https://dev.to/ankitmpatel</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ankitmpatel"/>
    <language>en</language>
    <item>
      <title>Complete guide to achieving WebSocket real-time communication with Laravel Broadcast using Pusher, Laravel echo &amp; Web socket</title>
      <dc:creator>Ankit Patel</dc:creator>
      <pubDate>Mon, 21 Dec 2020 17:01:04 +0000</pubDate>
      <link>https://dev.to/ankitmpatel/complete-guide-to-achieving-websocket-real-time-communication-with-laravel-broadcast-using-pusher-laravel-echo-web-socket-m29</link>
      <guid>https://dev.to/ankitmpatel/complete-guide-to-achieving-websocket-real-time-communication-with-laravel-broadcast-using-pusher-laravel-echo-web-socket-m29</guid>
      <description>&lt;p&gt;Nowadays, many advanced applications require real-time communication. Laravel has many inbuilt features to cover up the latest technologies and easy implementation. Laravel supports pusher, Redis, and socket.io to develop web socket interfaces.&lt;br&gt;
I'm going to discuss how to set up a web socket communication channel using a self-hosted pusher, laravel echo, and laravel web socket. Using this tutorial, you would be able to configure the setup for your own chat application.&lt;/p&gt;

&lt;p&gt;I've divided this tutorial into three steps,&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Server-side setup&lt;/li&gt;
&lt;li&gt;Client-side setup&lt;/li&gt;
&lt;li&gt;Final Execution - Create Broadcast Event &amp;amp; Listen to channel&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Server-Side Setup
&lt;/h2&gt;
&lt;h3&gt;
  
  
  Step 1
&lt;/h3&gt;

&lt;p&gt;If you're using broadcasting events, you should install a pusher package. Laravel - version 5.3 and above has built-in support for Pusher Channels as a Broadcasting backend.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;composer require pusher/pusher-php-server "~4.0" 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Pusher Compatible Laravel Websockets
&lt;/h4&gt;

&lt;p&gt;The laravel-websockets is a pure PHP, Pusher compatible WebSocket package for Laravel. This package allows you to leverage the full power of Laravel broadcasting without an external WebSocket provider or Node. For more information on installing and using this package, please consult its official documentation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;composer require beyondcode/laravel-websockets 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Change in .env&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;BROADCAST_DRIVER=pusher
APP_URL=http://127.0.0.1:8000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;you should add the host and port configuration key to your config/broadcasting.php and add it to the pusher section. The default port of the Laravel WebSocket server is 6001.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'pusher' =&amp;gt; [
    'driver' =&amp;gt; 'pusher',
    'key' =&amp;gt; env('PUSHER_APP_KEY'),
    'secret' =&amp;gt; env('PUSHER_APP_SECRET'),
    'app_id' =&amp;gt; env('PUSHER_APP_ID'),
    'options' =&amp;gt; [
        'cluster' =&amp;gt; env('PUSHER_APP_CLUSTER'),
        'encrypted' =&amp;gt; true,
        'host' =&amp;gt; '127.0.0.1',
        'port' =&amp;gt; 6001,
        'scheme' =&amp;gt; 'http'
    ],
],
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Run Webocket &amp;amp; Test
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan websocket:server
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open this URL : &lt;a href="http://127.0.0.1:8000/laravel-websockets"&gt;http://127.0.0.1:8000/laravel-websockets&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 2
&lt;/h3&gt;

&lt;p&gt;We use laravel broadcaster service, Let's uncomment following line from config/app.php&lt;br&gt;
&lt;br&gt;
 &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;App\Providers\BroadcastServiceProvider::class
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Step 3
&lt;/h3&gt;

&lt;p&gt;By installing pusher package in step 1, We get a new configuration file in the config folder, Let's configure config/broadcasting.php&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'pusher' =&amp;gt; [
            'driver' =&amp;gt; 'pusher',
            'key' =&amp;gt; env('PUSHER_APP_KEY'),
            'secret' =&amp;gt; env('PUSHER_APP_SECRET'),
            'app_id' =&amp;gt; env('PUSHER_APP_ID'),
            'options' =&amp;gt; [
                'cluster' =&amp;gt; env('PUSHER_APP_CLUSTER'),
                'useTLS' =&amp;gt; true,
            ],
        ],
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 4
&lt;/h3&gt;

&lt;p&gt;As we are not using pusher.com, It's time to change some dummy value in .env. The values shown below are just demoed purposes. It would be more realistic values on production. Why do we want to set dummy values here? You remember in step1 we install the pusher package that enables pusher on hour host, We're using the pusher broadcast driver supported by laravel so let's configure default environment variables.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PUSHER_APP_ID=123456
PUSHER_APP_KEY=scvbmzkmvc
PUSHER_APP_SECRET=xcnmcxdfgvc
PUSHER_APP_CLUSTER=mt1
BROADCAST_DRIVER=pusher
QUEUE_CONNECTION=sync
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 5
&lt;/h3&gt;

&lt;p&gt;Don't forget to check csrf tag in app.blade.php. Channel authentication will need csrf-token.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;meta name="csrf-token" content="{{ csrf_token() }}"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Configuration on Client Side
&lt;/h2&gt;

&lt;p&gt;We're going to add client-side code that enables communication from HTTP to a socket server using laravel echo&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 1
&lt;/h3&gt;

&lt;p&gt;You need client-side pusher js library that supports web browsers, web workers, Node.js and React Native.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install - save pusher-js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 2
&lt;/h3&gt;

&lt;p&gt;Laravel Echo is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by Laravel.&lt;br&gt;
npm install - save laravel-echo pusher-js&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 3
&lt;/h3&gt;

&lt;p&gt;Comment Vue.js in resources/js/app.js, if you're not using it. &lt;/p&gt;
&lt;h3&gt;
  
  
  Step 4
&lt;/h3&gt;

&lt;p&gt;Remove comment from resources/js/bootstrap.js and add Hosts&lt;br&gt;
&lt;br&gt;
 &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Echo from 'laravel-echo'; 
window.Pusher = require('pusher-js'); 
window.Echo = new Echo({
     broadcaster: 'pusher',
     key: process.env.MIX_PUSHER_APP_KEY,
     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
     forceTLS: true,
     wsHost: window.location.hostname,
     wsPort: 6001
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Your laravel-echo-server.json should look like this,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "authHost": "http://127.0.0.1:8000",
    "authEndpoint": "/broadcasting/auth",
    "clients": [
        {
            "appId": "626725232e738e727",
            "key": "4ac7dd96bc51f1f345344381230f2644737d"
        }
    ],
    "database": "redis",
    "databaseConfig": {
        "redis": {
      "port": "6379",
      "host": "127.0.0.1",
      "keyPrefix": ""
        }
    },
    "devMode": true,
    "host": null,
    "port": "8081",
    "protocol": "http",
    "socketio": {},
    "secureOptions": 67108864,
    "sslCertPath": "",
    "sslKeyPath": "",
    "sslCertChainPath": "",
    "sslPassphrase": "",
    "subscribers": {
        "http": true,
        "redis": true
    },
    "apiOriginAllow": {
        "allowCors": true,
        "allowOrigin": "http://localhost:80",
        "allowMethods": "GET, POST",
        "allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 5
&lt;/h3&gt;

&lt;p&gt;Compile client-side js and get ready!!!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Run - npm run dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Final Execution - Create Broadcast Event &amp;amp; Listen to channel
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Step 1 - Create Event
&lt;/h3&gt;

&lt;p&gt;Create TestEvent.php in App/Events&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class TestEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public $count;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
$this-&amp;gt;message =  'hello';
$this-&amp;gt;count = 1;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn(){
    return new Channel('test');
}
public function broadcastWith(){
    return ['message' =&amp;gt; str_random(15)];
}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 2- Listen channel in App.blade.php
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script src="{{ asset('/js/app.js') }}"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script&amp;gt;
Echo.channel('private-test')
    .listen('TestEvent', (e) =&amp;gt; {
         console.log(e);
    })
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Verify CSRF token once again!! Server-side setup - Step 5&lt;br&gt;
Execution&lt;/p&gt;

&lt;h4&gt;
  
  
  1. Start laravel echo server
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;laravel-echo-server start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2. Start websocket server
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan websocket:server
php artisan queue:work 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  3. Recompile app.js
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  4. Fire an event using php tinker, you should have a console log in the browser.
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan tinker
event(new \App\Events\TestEvent());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;We've implemented a basic setup of all components required to listen to the channel for real-time communication. We've seen how to set up a web socket with help of a pusher library using laravel broadcasting on the self-host. &lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
