This post is from the professional Laravel developer community, original link: learnku.com/laravel/t/1…

In my opinion, real-time communication is the future of apps. Socket services are not usually easy to implement, but the Laravel Echo service changes that.

In this article, I will briefly explain how to set up a Socket service that can run and broadcast events on this service. (github.com/tlaverdure/… , Laravel support documentation: laravel.com/docs/5.6/br…)

It’s completely free, you just have to run your own Socket service. You can also use Laravel’s default integrated Pusher, the only downside is that it is limited and you have to pay if you exceed the limit. I prefer to build these things myself.

Requirements:

  • Laravel Framework (version 5.6 is used for this tutorial)
  • Redis service
  • Basic Laravel knowledge

Laravel – echo – server installation

First we need to install laravel-echo-server globally, you just need to enter the following command in terminal.

 $ npm install -g laravel-echo-server
Copy the code

Once installed, open your Laravel app or start a new test project:

 $ composer create-project --prefer-dist laravel/laravel echo-test
Copy the code

Next to install Predis for our application:

 $ composer require predis/predis
Copy the code

After the installation is complete, switch to the root directory of the project and initialize the Socket service:

 $ laravel-echo-server init
Copy the code

After executing this command, you will be asked for some configuration information about the Socket service. You can fill in the following information according to your own situation:

Remember to turn off developer mode whenever you use it in production.

We can try to start the service to see if it works:

$ laravel-echo-server start
Copy the code

The output should look something like this:

Configure Laravel to make the Laravel Echo Server work properly

Open the BroadcastServiceProvider Providers array in your config/app.php file and uncomment it:

App\Providers\BroadcastServiceProvider::class,

This Provider will start broadcast routing (which you may have seen in the routes/channels.php file)

Open the. Env file and change the BROADCAST_DRIVER value to the one you defined when you started laravel-echo-server (Redis or Log). In this tutorial we will use the Redis driver. Also change QUEUE_DRIVER to whatever queue driver you like, in this case you can easily change it to Redis driver because you already have it installed and running earlier.

Next we must install the socket. IO client and the Laravel-echo package, which you can do by:

$ npm install --save socket.io-client
$ npm install --save laravel-echo
Copy the code

(You may need to run NPM Install to install Laravel and related dependencies before running this.)

Then open the resources/assets/js/bootstrap. Js file, or the introduction of yourself all js code base of js file.

Now we’ll add the code to start the Echo base service:

import Echo from 'laravel-echo'

window.io = require('socket.io-client');
window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + : '6001'
}); 
Copy the code

Now we’re ready to listen for messages on the channel! I’ll explain how to open channels in this tutorial, so let’s listen to our first channel:

window.Echo.channel('test-event')
    .listen('ExampleEvent', (e) => {
        console.log(e);
    });
Copy the code

We have JS code that tells the program that we subscribed to a channel named ‘test-event’ and listens for the’ ExampleEvent ‘event (which is the class name of the event, you can customize it as you like).

Let’s create this event class:

$ php artisan make:event ExampleEvent
Copy the code

This will create an event class called exampleEvent.php under the App/Events directory and let’s tweak this event class to make it work in our Socket service, First make sure your event class inherits from the ShouldBroadcast interface, like the following;

class ExampleEvent implements ShouldBroadcast

Next scroll down to the broadcastOn function and modify it so that we can broadcastOn the correct channel:

public function broadcastOn()
{
    return new Channel('test-event');
}
Copy the code

Let’s create a new function below so we can have some instance data:

public function broadcastWith()
{
    return [
        'data'= >'key'
    ];
}
Copy the code

This function is called when the event is called and will return data to your Socket service.

Now let’s try it! Open your routes/web.php file and add a test route:

Route::get('test-broadcast'.function(){
    broadcast(new \App\Events\ExampleEvent);
});
Copy the code

(There are several ways to broadcast the ExampleEvent class, in this example I used the broadcast() helper provided by Laravel, which seems to me to be the simplest way.)

Start queue listening:

$ php artisan queue:listen --tries=1
Copy the code

The browser opens a page with JS files (Laravel’s default welcome page), this is the first page, please do not close the next page, we have subscribed to the Socket service on this page.

Next open another page to access /test-broadcast, which will return a blank page, but it will be broadcast to your Socket service via your ExampleEvent class. Going back to our first page, open the browser console and you should see something like this:

As you can see, the data is presented in this form on our client. You can enter any data to broadcast through your ExampleEvent class, such data can be news updates, page updates, total views or more.

Because we have developer mode set in the Laravel-echo-server configuration, you can see all the basic information about the Socket service:

Now you have a basic Socket service installed and running! But that’s not all. You can do a lot more with this, such as providing a private channel for individual users to authenticate. (When you want to broadcast order updates or private messages)

To do this, I recommend you check out the Laravel documentation for more. There’s a lot you can do with this theme to make your app even more magical. You can find the corresponding documentation here:

Broadcasting – Laravel – The PHP framework for web artisans.laravel.com

Others: Run in the production environment

As I mentioned earlier, you must disable developer mode in the laravel-echo-server.json configuration file. Of course on the server you can ignore this file and reinitialize it, because your host may be different from the local one.

You also need to keep your Socket service running in your production environment. You can use Supervisor, but I usually use *PM2 *, which makes it easy and fast to manage your service. (http://pm2.keymetrics.io/)

Here is my basic socket.sh configuration using PM2:

#! /usr/bin/env bash
laravel-echo-server  start
Copy the code

After installing PM2, you can use the PM2 start socket.sh command to start the script and run your socket service.

I hope it helps you. This article covers the basics, but we will continue to discuss broadcast routing authorization and different broadcast channels.

Thanks for reading!