Justen  Hintz

Justen Hintz


How to use sockets in Laravel

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.



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

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


*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.


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.


| 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', 'ChatController@index');


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:


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');


The MessageSend class implements the ShouldBroadcast interface.


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


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


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.

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

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

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

                .listen('MessageSend', (e) => {
        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 = '';

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()) }}">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">

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

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!


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.


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' => [

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.

#laravel #php #web-development

What is GEEK

Buddha Community

How to use sockets in Laravel
Seamus  Quitzon

Seamus Quitzon


Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.


namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
    protected $fillable = [

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.


Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

I am Developer


Country State City Drop Down List using Ajax in Laravel

Here, i will show you how to create dynamic depedent country state city dropdown list using ajax in laravel.

Country State City Dropdown List using Ajax in php Laravel

Follow Below given steps to create dynamic dependent country state city dropdown list with jQuery ajax in laravel:

  • Step 1: Install Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Country State City Migration and Model File
  • Step 4: Add Routes For Country State City
  • Step 5: Create Controller For Fetch Country State City
  • Step 6: Create Blade File For Show Dependent Country State City in Dropdown
  • Step 7: Run Development Server


#how to create dynamic dropdown list using laravel dynamic select box in laravel #laravel-country state city package #laravel country state city drop down #dynamic dropdown country city state list in laravel using ajax #country state city dropdown list using ajax in php laravel #country state city dropdown list using ajax in laravel demo

How to Send E-mail Using Queue in Laravel 7/8

Today I will show you How to Send E-mail Using Queue in Laravel 7/8, many time we can see some process take more time to load like payment gateway, email send, etc. Whenever you are sending email for verification then it load time to send mail because it is services. If you don’t want to wait to user for send email or other process on loading server side process then you can use queue.

Read More : How to Send E-mail Using Queue in Laravel 7/8


Read Also : Send Mail Example In Laravel 8


#how to send e-mail using queue in laravel 7/8 #email #laravel #send mail using queue in laravel 7 #laravel 7/8 send mail using queue #laravel 7/8 mail queue example

Seamus  Quitzon

Seamus Quitzon


Laravel real time event broadcasting with socket.io example

In the today’s technogy age real time data has become an essential thing. So here, in this article i will share laravel real time event broadcasting with socket.io. Here in this example we will see how can we broadcast real times events.

Basically, to acheive this thing in our laravel application, we will use predis which is a laravel package, queue, socket.io, laravel-echo-server and event broadcasting.

So, we will need to install the above things which are not provided in the laravel appication by default. I will provide all the step to implement real time broadcasting event in the various steps from a fresh installation of laravel application. If you have already installed laravel application then you can directly jump on the next step. So without wasting our time let’s start the implementation process and follow all the steps as given below.

Step 1: Install Laravel

For installing fresh laravel application, you will just needto run the following command in your terminal or command prompt.

composer create-project --prefer-dist laravel/laravel realtimeapp

I have given a name realtimeapp to this application, you are frre to give the name of your choice.

Now, run the following command to give permission to the storage and cache directories.

sudo chmod -R 777 /var/www/html/realtimeapp/storage
sudo chmod -R 777 /var/www/html/realtimeapp/bootstrap/cache<br><br>

Step 2: Install predis

In this second step, we will need to install predis. So open your terminal and run the following command.

composer require predis/predis

composer require predis/predis

Step 3: Create event for broadcasting

Now we will need to create an event for broadcasting and in the event file we will set channal and write message. So run the following command to create event.

php artisan make:event SendMessage

Above command will create an event file SendMessage.php file under app/Events directory. So open this file and update it like below.



namespace App\Events;

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

class SendMessage implements ShouldBroadcastNow
    use InteractsWithSockets, SerializesModels;

    public $data = ['asas'];

     * Create a new event instance.
     * @return void
    public function __construct()


     * Get the channels the event should broadcast on.
     * @return \Illuminate\Broadcasting\Channel|array
    public function broadcastOn()
        return new Channel('user-channel');

     * The event's broadcast name.
     * @return string
    public function broadcastAs()
        return 'UserEvent';
     * The event's broadcast name.
     * @return string
    public function broadcastWith()
        return ['title'=>'Notification message will go here'];

#laravel #how to broadcast events in laravel #laraevl socket.io #laravel broadcasting event #laravel event broadcasting #laravel realtime event broadcasting with socket.io

I am Developer


Crop and Resize Image Before Upload In Laravel Using with jQuery Copper JS

Crop and resize image size before upload in laravel using jquery copper js. In this post, i will show you how to crop and resize image size in laravel using jQuery copper js in laravel.

This laravel crop image before upload using cropper js looks like:

laravel crop image before upload

Laravel Crop Image Before Uploading using Cropper js Tutorial

Laravel crop image before upload tutorial, follow the following steps and learn how to use cropper js to crop image before uploading in laravel app:

  • Step 1: Install New Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Migration & Model
  • Step 4: Add Route
  • Step 5: Create Controller By Artisan
  • Step 6: Create Blade View
  • Step 7: Make Upload Directory
  • Step 8: Start Development Server

Read More => https://www.tutsmake.com/laravel-crop-image-before-upload-using-jquery-copper-js/

Live Demo Laravel Crop image Before Upload.

#laravel crop image before upload, #laravel crop and resize image using cropper.js #ajax image upload and crop with jquery and laravel #crop and upload image ajax jquery laravel #crop image while uploading with jquery laravel #image crop and upload using jquery with laravel ajax