How to use sockets in Laravel

How to use sockets in Laravel

In this article, you'll learn how to use sockets in Laravel App by making a chatbox.

In this article, you'll learn how to use sockets in Laravel App by making a chatbox.

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.

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 <em>PUSHER_APP_ID</em>, <em>PUSHER_APP_KEY</em>, <em>PUSHER_APP_SECRET</em> and <em>PUSHER_APP_CLUSTER</em> for this. Furthermore, change the <em>BROADCAST_DRIVER</em> 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.

<?php

namespace App\Http\Controllers;

use App\Events\MessageSend;
use Illuminate\Http\Request;

class ChatController extends Controller
{
    public function index(Request $request)
    {
        $message = $request->input('message', '');

        if (strlen($message)) {
            event(new MessageSend($message));
        }
    }
}

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

<?php

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::post('/message', '[email protected]');

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:

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class MessageSend implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    public function __construct($message)
    {
        $this->message = $message;
    }

    public function broadcastOn()
    {
        return new Channel('chatbox');
    }
}

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

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.

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.

<template>
    <div class="chatbox p-3">
        <div class="messages" v-if="messages.length">
            <div class="message" v-for="message in messages">
                <span class="d-inline-block">{{ message }}</span>
            </div>
        </div>

        <div class="row mt-5">
            <div class="col-3">
                <input type="text" class="form-control" v-model="textMessage"></input>
            </div>
        </div>

        <div class="row mt-2">
            <div class="col">
                <button class="btn btn-primary" @click="sendMessage()">Send</button>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                textMessage: '',
                messages: [],
            }
        },
        created() {
            this.addMessage('You joined the chatbox.');

            Echo.channel('chatbox')
                .listen('MessageSend', (e) => {
                    this.addMessage(e.message);
                });
        },
        methods: {
            addMessage(message) {
                let date= new Date();
                let timestamp = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();

                this.messages.push(timestamp + ' ' + message);
            },
            sendMessage() {
                axios.post('/api/message', {message: this.textMessage});
                this.textMessage = '';
            }
        }
    }
</script>

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

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Chatbox</title>

        <script src="{{ asset('js/app.js') }}" defer></script>
        <script src="{{ asset('js/bootstrap.min.js') }}"></script>
        <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    </head>
    <body>
        <div id="app">
            <chatbox-component></chatbox-component>
        </div>
    </body>
</html>

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.

Advantages of Hiring PHP Developer for your Website Project

Advantages of Hiring PHP Developer for your Website Project

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is...

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is to learn the language yourself. That’s why PHP developers are there to make your life easy. This article will give us the advantages and requirements of Hire PHP Developer for our very own website project.

First of all, let us understand the value the right developer brings to the project and why it is important for your business.

A website is a major component of any company/business and is very important for its face value, the way it represents the company on the internet is critical for any business to succeed. This is the reason why companies are looking for PHP developers who can develop their webpage.

If you're planning to do an online business, your PHP programmer will be the first person to transfer your thinking onto the webpage. You should, therefore, employ developers from PHP to make your hypothetical idea a reality.

With this software programming language, PHP developers all-around can easily build website frameworks, web content management systems, web template systems, and various other web-based designs.

Some of the reasons why we need to outsource these developers are:

Not everyone is the best in each field, all of us have our specific skills and talents hence, PHP developers are also the best at what they do. The time and money spent on the training of the in house employees would be saved if the professional PHP developers are hired. Instead of multitasking, if the employees were to focus on what they’re good at it would increase productivity too.

The PHP developers would be much more professional than the in-house workers. It would lead to the seriousness of work. Hence, on-time delivery is guaranteed with hired PHP developers.

In addition to these benefits, you would also be able to track your project through every stage in constant communication with your online team. These advantages make it incredibly popular and smart to hire a PHP developer.

The PHP developers have in-depth knowledge of PHP, HTML and various frameworks in terms of technical capabilities. Hiring PHP developers are advised to give your website a professional look based on PHP.

Much of web success depends on the involvement of social media. The developer can add to your social networking pages a feature that explicitly redirects visitors. In addition, SEO experts also suggest better connections to the website's social network.

Just like a tailor stitches our dresses according to our preferences and is ready to make last-minute changes. A PHP developer will also be available at the nick of your call to make the website just the way you want it to be and have a customized solution for every problem.

Read also: Why & How to Hire Dedicated PHP Developer

At some point in your business, you’re going to have problems regarding your webpage due to the rapidly changing technology, instead of struggling with ideas like these and not being able to come up with an appropriate solution a PHP web developer could help us with our problems just like any technician would help us with the problems we face in our offices or any architect would help us with designing the structure of a building or any interior designer would help us with setting up our home. The PHP development company are hubs of workers who would help us overcome these problems and are always there.

Source by

Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]

Laravel Framework Development Services | Laravel Web Development

CMARIX is leading Laravel Web application Development Service Provider with the track record of implementing diverse high-performance Laravel web applications with skilled Laravel developer team for clients across the globe<a href="https://www.cmarix.com/laravel-framework-development-services.html?utm_source=SB" target="_blank">.Continue</a>

CMARIX is leading Laravel Web application Development Service Provider with the track record of implementing diverse high-performance Laravel web applications with skilled Laravel developer team for clients across the globe.Continue