Table of Contents
Getting your Trinity Audio player ready...
|
While we are developing modern web applications we usually perform page refresh. but with some requirements of the features have to send or get real-time data without page refresh.
so we can achieve that with WebSocket via Laravel broadcasting. which helps to update real-time data from the server.
For example: if I want to make an admin panel that shows on time how many customers are Registered in my system. Without page refresh then we can achieve via WebSockets and for that laravel provides.
In this situation when we have to update real-time data here, Laravel works wonderfully to “broadcast” your server-side Laravel events over a WebSocket connection. Broadcasting your Laravel events allows you to share the same event names and that data between your server-side Laravel application and your client-side JavaScript application, as server-side to client side.
And then the basic picture comes with broadcasting which is simple as in the frontend clients connect to the named channel, with that your Laravel web application broadcasts events to these channels in the backend server. And we can add changes in events that we want to show in are front end as per are project and feature requirements.
As per above example, when a new customer registered in the system, and that request is passed to server and via are code and implemented features wise that customer will register but to show real time data in the admin panel. Then websocket will come into this situation when we have to show real time data without page refresh , so the code’s flow will communicate with the server over websocket which will send your data to the front end .
So here when the server will get a request then it will accept and perform actions and return a channel to frontend for update data.
Here admin can get all track of that customers as what they are purchasing,
what’s in the cart without page refresh.
So in that same flow will perform as every customer will add any product in that cart
Or purchase anything server will get request and it will accept and perform flow of are
Features and return a channel with data to the frontend for showing the latest updated data.
Based on this example or any other features of your application, we took channels for Perform communication between customer and server to frontend. And we can achieve this in the Laravel using Broadcast.
Requirements to perform this Broadcasting :
Let’s gather what we actually required to use broadcasting with WebSocket to implement server-side requests to show data in the front end without page refresh. And show in seconds as realtime.
- First is a driver , To implement and exchange real time with broadcast in the Laravel.
- Here we can use so many things as a driver laravel echo server , pusher as a driver if you want or as per requirement possible to use pusher , and also you can use redis driver.
- And as per your requirement and choice you can change driver related things in
Environment file which is called .env file in the root folder of the application’s folder structure . and add changes in the config/database.php file .
Your Broadcasting redis instance and laravel-echo-server ‘s redis instance both should be the same , there should be no difference in both of them , and In the redis_prefix there will be a prefix so it should be corresponding to the laravel-echo-server ‘s prefix.
Here We Go:
In our application, we have an echo server which is running. and to perform a connection to the echo server the main requirement will be socket. io-client for the server side and for the frontend side laravel-echo.
- Here socket.io-client will connect to the actual socket server , laravel-echo will connect with the front end part and work as middleware to pass data .
- For the front end part Here is the first Echo instance which we have to set in the resources/js/bootstrap.js file.
– In the Windows.echo we have a broadcaster property and we have to pass socket .io in that . and in the host property we have to pass the server’s IP ADDRESS And PORT number.
broadcaster: ‘socket.io’, // broadcaster
host: window.location.hostname + ‘:2001’//host
});
▲
- Then run this yarn run dev or npm run dev any of the commands based on your project’s packages and library.
- And create a JS file inside a public/js folder. and check the web socket connection with the server via the developer tools network tab.
- For the Back end part for broadcasting a new customer register, we have to pass a new entry count from the backend web server to web socket server, and for passing new customer count with their details we have to pass that over the channels.
Here there are mainly 3 types of channels. Let’s look into that.
- . Public Channel class ( here no requirement for auth)
- . Private Channel class ( here requirement for auth to connect this channel)
- . Presence Channel Class ( here requirement for auth to connect this channel)
- Here as per the basic flow of laravel we can do auth with CSRF(Cross-Site Request Forgery) Token or session.
- Every time front performs connect to the server via Public and Presence class they will require auth. Once we pass a token or session it will forward that auth-related data request calls to the backend for confirmation as this user is authenticated or not authenticated.
- if the backend server returns true as this user is authenticated then the front end can connect with the web socket server and perform channel operations and exchange data.
- To perform with broadcasts we have to create events. For that, there is a command which you can use.
php artisan make:event CusotmerRegisterEvent
- Once you run this command it will create a new event, and once you update it will look like this.
<?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class CusotmerRegisterEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
private $type, $customer;
public function __construct ($type, $customer) {
$this->type = $type;
$this->customer = $customer;
}
public function broadcastAs () {
return ‘activity-monitor’;
}
public function broadcastQueue () {
return ‘broadcastable’;
}
public function broadcastWith () {
return [
‘id’ => $this->customer->customer_id,
‘name’ => $this->customer->name,
‘customer_name’ => $this->customer->customer_name,
‘action’ => ucfirst(strtolower($this->type)),
‘on’ => now()->toDateTimeString(),
];
}
public function broadcastOn () {
return new Channel(‘activities’);
} }
▲
We can call this event class from the controller. As per our example, we can take the situation as are customer registers in our system so When customers register that time, store all data per our requirements and flow then call events.
event(new CusotmerRegisterEvent(‘register’, $customer)); // when customer register
This will call the CusotmerRegisterEvent event class with parameters such as type and customer data.
- And in your front-end code. we can set it in the welcome.blade.php file.
<script src=“{{ asset(‘js/app.js’) }}”></script>
<!– add a new script tag, and listen for the upcoming event for the customer’s actions –>
<script type=“text/javascript”>
// Echo is available via window.Echo, in app.js file
Echo.channel(‘activities’)
.listen(‘.activity-monitor’, (e) => {
console.log(e);
});
</script>
▲
- Here the echo. channel method will listen to the same channel which we defined in our CusotmerRegisterEvent’s broadcastOn method.
- And the .listen method listens for the same name which we defined in our broadcastAs method. We can see them . (dot) at the beginning of the name.
- So you can use any custom event name as your coding requirement.
- Here we are ready to see , as once any of the customers will register that data will reflect to the admin panel in real time . and the same way we can implement cart and purchase-related features with real time updates of data via this flow.
About Author
Tarun Bansal - Technical Head
Tarun is a technology enthusiast with a flair for solving complex challenges. His technical expertise and deep knowledge of emerging trends have made him a go-to person for strategic tech initiatives. Passionate about innovation, Tarun continuously explores new ways to drive efficiency and performance in every project he undertakes.