avatarDaan

Summary

This article provides a comprehensive guide on implementing real-time sockets in a Laravel application, specifically demonstrating the creation of a chatbox using Pusher for event broadcasting.

Abstract

The article titled "Guide to using sockets in your Laravel application" outlines the process of integrating sockets for real-time communication in a Laravel environment. It begins with an introduction to the importance of sockets for modern web development, particularly for features like notifications or chat applications. The author then delves into a step-by-step tutorial, starting with the backend setup, which includes installing Pusher via Composer, configuring Pusher credentials in the .env file, and creating a chat controller to handle incoming messages and broadcast events. The tutorial progresses to the frontend development, detailing the use of Laravel Echo and Pusher-js to receive broadcasted messages and updating the user interface in real-time. The article also addresses potential debugging issues and provides solutions for common problems, such as the BroadcastException. The guide concludes with encouragement for readers to implement the demonstrated sockets functionality and to explore the author's other Laravel-related content.

Opinions

  • The author believes that sockets are essential for real-time web features like chat applications and notifications.
  • Pusher is recommended as a broadcasting service, although alternatives like Redis or Socket.io are mentioned.
  • The article suggests that using Laravel Echo simplifies the process of subscribing to channels and listening to broadcasts.
  • The author emphasizes the importance of debugging tools, such as Pusher's Debug Console, for troubleshooting socket-related issues.
  • The author is open to feedback and invites readers to engage with their content by commenting or suggesting future topics.
  • A cost-effective AI service, ZAI.chat, is endorsed as an alternative to ChatGPT Plus (GPT-4), offering similar performance at a lower price.

Guide to using sockets in your Laravel application

Nowadays sockets are very popular in web development. Sockets allow real-time communication between the browser of a client and the server. There are a lot of use cases for sockets. For example, sockets could be used for notifications or a chat application. In this article I will show you how to use sockets in your Laravel application by making a chatbox. I will be using Pusher to broadcast my events, but you could also use Redis or Socket.io for broadcasting. In the first part of this article we will make the backend part of the application and in the second part we will be focusing on the frontend.

Part 1: Backend

Pusher

Since we are going to broadcast our events over Pusher we should install it via Composer.

composer require pusher/pusher-php-server "~3.0"

Note: To use Pusher you will need an account. You can create a free account at https://pusher.com

Once you have created your Pusher account, you have to create an app in Pusher. After you have created the app you should add the app id, app key, app secret and cluster to your .env file. Use the PUSHER_APP_ID, PUSHER_APP_KEY, PUSHER_APP_SECRET and PUSHER_APP_CLUSTER for this. Furthermore, change the BROADCAST_DRIVER to pusher.

The credentials will be displayed in the Pusher dashboard, once you have selected your app

Time to start making the chatbox

Now that we have installed the dependencies and setup our Pusher app, it is time to start making the chatbox. Let’s have a quick overview of what we are about to do. We will create a Vue component for the chatbox which will send a request to an API controller with the message that is send by the user. This will be implemented in the second part of this article. For the backend we will create an API controller that will broadcast an event to inform all other clients about the message that was send to the chatbox.

Creating the controller

Let’s start by creating a controller, which will handle incoming requests:

php artisan make:controller ChatController

The implementation of the controller will be very simple. If the request contains a message we will fire an event, else we do nothing. This event will broadcast the message to all clients.

We will also need to create a route in the routes/api.php file.

Event

As we saw in the ChatController an event, called MessageSend, get’s fired. This event should be broadcasted to the other clients, to let them know that a message was send to the chatbox. First things first, let’s create the event:

php artisan make:event MessageSend

The MessageSend class will broadcast on the chatbox channel, which is a public channel. This is defined in the broadcastOn method.

This is what the implementation looks like:

Note: The MessageSend class implements the ShouldBroadcast interface.

BroadcastServiceProvider

Before we can starting broadcasting our events the App\Providers\BroadcastServiceProvider should be registered. This can be done by uncommenting this provider in the providers array in the config/app.php file.

Uncomment the BroadcastServiceProvider

Since we have made some changes in our configuration we have to run the following command to fix our configuration cache file:

php artisan config:cache

Part 2: Frontend

Receiving broadcasts

To receive broadcasts we are going to use a Javascript Library, called Laravel Echo. This library makes it very easy to listen to broadcasts and subscribe to channels. We will also install pusher-js since we are using Pusher for broadcasting.

npm install --save laravel-echo pusher-js

Once we have installed Laravel Echo and Pusher, we have to create an instance of Laravel Echo in the application. On the bottom of the resources/js/bootstrap.js file is some code which creates the Laravel Echo instance for you. Uncomment this part of the code.

Uncomment the Laravel Echo code

Chatbox

As mentioned previously, we are going to create a Vue component that sends a request to our API whenever a message is send. We are going to create that Vue component right now.

Create a ChatboxComponent.vue in the resources/js/components folder. This component contains a very simple form that sends a request to the /api/message endpoint. Futhermore, this component listens to the MessageSend event on the chatbox channel. Whenever it receives a message, it will add it to the chatbox.

Now that we have created the ChatboxComponent let’s change the welcome.blade.php so that it actually uses the component.

To make sure that our newly created component gets registered we have to uncomment the following to lines in the resources/js/app.js file.

These two lines of code will automatically register your Vue components. Do not forget to run npm run watch .

Chitty chat

We can now start a conversation in the chatbox. To test the application open up two tabs in your browser, one of them in incognito mode, and just start typing!

The chatbox in action in two tabs!

Debugging

If you are running into any issues there is a way to debug your sockets. Pusher has a great debug console which will log any activity happening in your sockets. Just go to the Pusher dashboard and select the Debug console tab. You can check if a client connects to Pusher and if events are being broadcasted.

BroadcastException

Depending on the environment that you are developing on, you may receive a BroadcastException when trying to broadcast the event. This can be fixed by adding the following lines of code to the pusher.options array in the config/broadcasting.php file.

'curl_options' => [
    CURLOPT_SSL_VERIFYHOST => 0,
    CURLOPT_SSL_VERIFYPEER => 0,
],

Congratulations! The chatbox is finished. I hope this article helped you implementing sockets in Laravel. Make sure to check out my other posts aswell, a lot of my content is about Laravel. Please feel free to leave a comment if you have any feedback, questions or want me to write about another Laravel related topic.

Happy coding!

Laravel
PHP
Programming
Software Development
Web Development
Recommended from ReadMedium
avatarIsmat Babirli
Develop Microservice with Laravel

12 min read