Ticker

6/recent/ticker-posts

Real-time Laravel Ratchet Websocket Chat Application

Real-time Laravel Ratchet Websocket Chat Application https://i.ytimg.com/vi/8ie5PTBY77E/hqdefault.jpg

In this tutorial, we will discuss How to make Real Time Chat Application in Laravel 9 Framework by using Ratchet Web Socket Library. In this tutorial, we will build Real-time Chat Application in which we users can do real time conversation via this Chat Application. So if you are searching tutorial on Real-time Laravel Chat Application with Web Socket, then you have land on the right place because here, we will build Real-time Chat Application using Laravel and Ratchet Web Socket.

Under this tutorial, we will not use any paid messaging service but for send and receive chat message in real-time here we will use Ratchet Web Socket Library with Laravel 9 framework. So at backend we will use Laravel 9 framework, Ratchet Websocket Library and MySQL database and at front-end we will use Vanilla JavaScript and Bootstrap 5 Library. So this web technology we will use for build real time chat application in Laravel framework by using Ratchet Websocket Library. In the current time, in every web application that requires real time communication so for implement real time communication, here we have use Ratchet Websocket Library with Laravel framework and by using this Library we can implement real time communication of data and build chat application.

What is Ratchet WebSocket?

Ratchet WebSocket is PHP Library which will provides tools to developer for create real-time web application in which client and server are connected in bi-directional, so client directly send message to other client via this Web Socket. It will create tunnel between two or multiple client and they can sed and receive message in real-time. This Ratchet WebSocket will make persistent connection from browser to the server and once the connection has been established then that connection will be open until client or server decide to close it. So in open connection mode, the client send message to other client.

 

Web Technology used for Build Laravel Chat Application

Server Side

  • Laravel 9 Framework
  • MySQL Database
  • Ratchet WebSocket
  • Composer

Client Side

  • Vanilla JavaScript
  • Bootstrap 5 Library

Architecture of Laravel Ratchet Web Socket Chat Application

In Below image you can find the basic architecture of Laravel Ratchet Web Socket Chat Application.

Features of Laravel Ratchet WebSocket Chat Application

Below you can find different feature of Real-time Laravel Ratchet WebSocket Chat Application.

  1. Chat Application Registration
  2. Chat Application Login
  3. Manage Profile
  4. List Unconnected User with Send Chat Request Button
  5. Search User and List with Send Chat Request Button
  6. Send Chat Request to User
  7. Display User Chat Request in Notification Area
  8. Approve or Reject User Chat Request in Notification Area
  9. Display Approve Chat Request User in Connected User Area
  10. List Approve Chat Request User in Connected User Area
  11. Make Chat Area with Send Chat Button
  12. Reset Chat Area
  13. Load Chat history when User has select another user to Chat
  14. Send Chat Message to One to One User
  15. Whatsup like Message Send Read status using icon
  16. Display number of unread message notification
  17. Display User is Online or Not using icon
  18. Display Whatsup like User Last Seen Detail

Below you can find step by step process for build Laravel Ratchet WebSocket Chat Application.

  1. Install Laravel 9 Application
  2. Make Database Connection
  3. Create Model Class
  4. Download & Install Ratchet WebSocket Library
  5. Create Controller
  6. Create View Blades Files
  7. Set Route of Controller Method
  8. Run Laravel 9 Application

Step 1 – Install Laravel 9 Application

In first step, we want to download fresh copy of Laravel 9 framework. So we have goes to command prompt and goes to directory where we can run our PHP code. So after goes into that directory, we have to run following command which will make custom_login directory and under that directory it will download and install Laravel 9 Application.


composer create-project laravel/laravel custom_demo

Step 2 – Make Database Connection

Once we have download and install Laravel 9 Application, now we first we want to make MySQL database connection. So for this, we have to open .env file and under this file, we have to define MySQL database configuration. So after define this configuration details it will make MySQL database connection with Laravel 9 Application.

.env


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=

So after make MySQL Database connection, now we want to make user table under mysql database. So here we will use default user table of Laravel 9 Application. So here user table defination has been stored under database/migrations directory. So for create table in MySQL database from Laravel Application, we have to run following command. So this command will create users table under MySQL database from this Laravel 9 Application.


php artisan migrate

Now we want to add four table column in users table, so for this, in command prompt we have to following command.


php artisan make:migration update_users_table --table=users

So this command has been create alter user table migration file and under this file we have to define column details which you can seen below.

database/migrations/2022_09_06_111722_update_users_table.php


string('token');
            $table->integer('connection_id');
            $table->enum('user_status', ['Offline', 'Online']);
            $table->string('user_image');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('token');
            $table->dropColumn('connection_id');
            $table->dropColumn('user_status');
            $table->dropColumn('user_image');
        });
    }
};


Next We need to create chats table, so for this, we have to goest to command prompt and run following command.


php artisan make:model Chat -m

So this command will create migration file and Chat Model Class file. First we have to open Chats table migration file and under this file, we have to define table column defination.

database/migrations/2022_09_06_112831_create_chats_table.php


id();
            $table->integer('from_user_id');
            $table->integer('to_user_id');
            $table->string('chat_message');
            $table->string('message_status');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('chats');
    }
};


And in MySQL database part, we have to create chat_requests table. So for this, we have goes to command prompt and run following command.


php artisan make:model Chat_request -m

This command will make create chat_requests table migration file and Chat_request.php Model class file. Here first we have to open create chat_requests table migration file and under this file, we have to define table column details which you can seen below.


id();
            $table->integer('from_user_id');
            $table->integer('to_user_id');
            $table->enum('status', ['Pending', 'Approve', 'Reject']);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('chat_requests');
    }
};


Now we want to create two new table and alter existing table, so for this we have goes to command prompt and run following command.


php artisan migrate

So this command will create chats table and chat_requests table and add four table column in users table from this laravel application.

Step 3 – Create Model Class

Under this Laravel Chat Application we will use Model class for database operation. Model class file will be created when we have create MySQL table migration file. Under this tutorial, we have create User.php, Chat.php and Chat_request.php model class file. So under this file, we have to define MySQL table column details, which you can seen below.

app/Models/User.php



     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'token',
        'connection_id',
        'user_status',
        'user_image'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}


app/Models/Chat.php



app/Models/Chat_request.php



Step 4 - Download & Install Ratchet WebSocket Library

In this Laravel Chat Application, we have use Ratchet WebSocket Library for make Real-time Chat Application. So in this part, we will download and install Ratchet WebSocket Library. So for download Ratchet WebSocket Library. We have goes to command prompt and run following command.


composer require cboden/ratchet

This command will download and install Ratchet Websocket Library under vendor. After this we want to create WebSocket Server file. So for this, we have to goes to command prompt and run following file.


php artisan make:command WebSocketServer --command=websocket:init

After run above command, so it will create Websocket Server file in app/Console/Commands/WebSocketServer.php under this directory. So we have to open this file, and under this file we have to define following code for make Ratchet WebSocket server.

app/Console/Commands/WebSocketServer.php


run();
    }
}


So this WebSocket Server will be run on the 8090 port number. Next we have to create Socket Controller file. So for this, we have goes to command prompt and run following command.


php artisan make:controller SocketController

So this command will make SocketController.php controller file under app/Http/Controllers directory, and you can find source code of this controller file under this Create Controller Steps.

Step 5 - Create Controller

Under this Laravel Ratchet Chat Application, first we want to make controller for Login and Registration page. So for create Controller for Chat Application Login and Registration page, we have goes to command prompt and run following command.


php artisan make:controller SampleController

This command will make SampleController.php file under app/Http/Controllers directory. So we have to open this directory and write following code for make Login Registration and Logout feature for this Real-time Laravel Ratchet WebSocket Chat Application.

app/Http/Controllers/SampleController.php


validate([
            'name'         =>   'required',
            'email'        =>   'required|email|unique:users',
            'password'     =>   'required|min:6'
        ]);

        $data = $request->all();

        User::create([
            'name'  =>  $data['name'],
            'email' =>  $data['email'],
            'password' => Hash::make($data['password'])
        ]);

        return redirect('login')->with('success', 'Registration Completed, now you can login');
    }

    function validate_login(Request $request)
    {
        $request->validate([
            'email' =>  'required',
            'password'  =>  'required'
        ]);

        $credentials = $request->only('email', 'password');

        if(Auth::attempt($credentials))
        {
            $token = md5(uniqid());

            User::where('id', Auth::id())->update([ 'token' => $token ]);

            return redirect('dashboard');
        }

        return redirect('login')->with('success', 'Login details are not valid');
    }

    function dashboard()
    {
        if(Auth::check())
        {
            return view('dashboard');
        }

        return redirect('login')->with('success', 'you are not allowed to access');
    }

    function logout()
    {
        Session::flush();

        Auth::logout();

        return Redirect('login');
    }

    public function profile()
    {
        if(Auth::check())
        {
            $data = User::where('id', Auth::id())->get();

            return view('profile', compact('data'));
        }

        return redirect("login")->with('success', 'you are not allowed to access');
    }

    public function profile_validation(Request $request)
    {
        $request->validate([
            'name'      =>  'required',
            'email'     =>  'required|email',
            'user_image'   =>   'image|mimes:jpg,png,jpeg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000'
        ]);

        $user_image = $request->hidden_user_image;

        if($request->user_image != '')
        {
            $user_image = time() . '.' . $request->user_image->getClientOriginalExtension();

            $request->user_image->move(public_path('images'), $user_image);
        }

        $user = User::find(Auth::id());

        $user->name = $request->name;

        $user->email = $request->email;

        if($request->password != '')
        {
            $user->password = Hash::make($request->password);
        }

        $user->user_image = $user_image;

        $user->save();

        return redirect('profile')->with('success', 'Profile Details Updated');
    }
}


app/Http/Controllers/SocketController.php


clients = new SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);

        $querystring = $conn->httpRequest->getUri()->getQuery();

        parse_str($querystring, $queryarray);

        if(isset($queryarray['token']))
        {
            User::where('token', $queryarray['token'])->update([ 'connection_id' => $conn->resourceId ]);
        }


    }

    public function onMessage(ConnectionInterface $conn, $msg)
    {
        $data = json_decode($msg);

        if(isset($data->type))
        {
            if($data->type == 'request_load_unconnected_user')
            {
                $user_data = User::select('id', 'name', 'user_status', 'user_image')
                                    ->where('id', '!=', $data->from_user_id)
                                    ->orderBy('name', 'ASC')
                                    ->get();

                $sub_data = array();

                foreach($user_data as $row)
                {
                    $sub_data[] = array(
                        'name'      =>  $row['name'],
                        'id'        =>   $row['id'],
                        'status'    =>  $row['user_status'],
                        'user_image'=>  $row['user_image']
                    );
                }

                $sender_connection_id = User::select('connection_id')->where('id', $data->from_user_id)->get();

                $send_data['data'] = $sub_data;

                $send_data['response_load_unconnected_user'] = true;

                foreach($this->clients as $client)
                {
                    if($client->resourceId == $sender_connection_id[0]->connection_id)
                    {
                        $client->send(json_encode($send_data));
                    }
                }
            }

            if($data->type == 'request_search_user')
            {
                $user_data = User::select('id', 'name', 'user_status', 'user_image')
                                    ->where('id', '!=', $data->from_user_id)
                                    ->where('name', 'like', '%'.$data->search_query.'%')
                                    ->orderBy('name', 'ASC')
                                    ->get();

                $sub_data = array();

                foreach($user_data as $row)
                {
                    $sub_data[] = array(
                        'name'  =>  $row['name'],
                        'id'    =>  $row['id'],
                        'status'=>  $row['user_status'],
                        'user_image' => $row['user_image']
                    );
                }

                $sender_connection_id = User::select('connection_id')->where('id', $data->from_user_id)->get();

                $send_data['data'] = $sub_data;

                $send_data['response_search_user'] = true;

                foreach($this->clients as $client)
                {
                    if($client->resourceId == $sender_connection_id[0]->connection_id)
                    {
                        $client->send(json_encode($send_data));
                    }
                }
            }
        }
    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);

        $querystring = $conn->httpRequest->getUri()->getQuery();

        parse_str($querystring, $queryarray);

        if(isset($queryarray['token']))
        {
            User::where('token', $queryarray['token'])->update([ 'connection_id' => 0 ]);
        }
    }

    public function onError(ConnectionInterface $conn, Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()} n";

        $conn->close();
    }
}


Step 6 - Create View Blades Files

In this steps, we have to make Blade views file for display HTML output in the browser. So first we have to make Login, Registration and Master template for this Laravel Chat Application. So we have goes to resources/views directory and under this directory, we have to make following views blade file.

resources/views/main.blade.php





    
    
    Laravel 9 Custom Login Registration
    
    



    
    
@yield('content')

resources/views/login.blade.php


@extends('main')

@section('content')

@if($message = Session::get('success'))

{{ $message }}
@endif
Login
@csrf
@if($errors->has('email')) {{ $errors->first('email') }} @endif
@if($errors->has('password')) {{ $errors->first('password') }} @endif
@endsection('content')

resources/views/registration.blade.php


@extends('main')

@section('content')

Registration
@csrf
@if($errors->has('name')) {{ $errors->first('name') }} @endif
@if($errors->has('email')) {{ $errors->first('email') }} @endif
@if($errors->has('password')) {{ $errors->first('password') }} @endif
@endsection('content')

resources/views/dashboard.php


@extends('main')

@section('content')

Connected User
Chat Area

Notification
@endsection('content')

resources/views/profile.php


@extends('main')

@section('content')

@if($message = Session::get('success'))
{{ $message }}
@endif
Profile
@csrf @foreach($data as $row)
@if($errors->has('name')) {{ $errors->first('name') }} @endif
@if($errors->has('email')) {{ $errors->first('email') }} @endif
@if($errors->has('user_image')) {{ $errors->first('user_image') }} @endif
@if($row->user_image != '') @endif
@endforeach
@endsection('content')

Step 7 - Set Route of Controller Method

Next we have to set route of Controllers class method. So for this, we have to open routes/web.php and under this file, we have to write following code for set route for Controllers Class method.

routes/web.php


group(function(){

    Route::get('login', 'index')->name('login');

    Route::get('registration', 'registration')->name('registration');

    Route::get('logout', 'logout')->name('logout');

    Route::post('validate_registration', 'validate_registration')->name('sample.validate_registration');

    Route::post('validate_login', 'validate_login')->name('sample.validate_login');

    Route::get('dashboard', 'dashboard')->name('dashboard');

    Route::get('profile', 'profile')->name('profile');

    Route::post('profile_validation', 'profile_validation')->name('sample.profile_validation');

});


Step 8 - Run Laravel 9 Application

Now we have come to last step and under this step we have to check output in the browser. So before check output in the browser, first we need to start Laravel server. So we have goes to command prompt and run following command.


php artisan serve

This command will start Laravel server and it will provide use base url of our Laravel Ratchet WebScoket Chat Application, so we have goes to browser and paste following url in browser for check output in the browser.


http://127.0.0.1:8000/login

This is partial code and we will update remaining code on every publish of video tutorial. So check this tutorial, on every publish of new video tutorial of this Real-time Laravel Ratchet WebSocket Chat Application.

In this tutorial, we will discuss How to make Real Time Chat Application in Laravel 9 Framework by using Ratchet Web Socket Library. In this tutorial, we will build Real-time Chat Application in which we users can do real time conversation via this Chat Application. So if you are searching tutorial on Real-time Laravel Chat…
and,this,have,laravel chat app,laravel chat application,laravel chat application with websocket,laravel chat script,laravel websockets,real time chat application in laravel,real time chat laravel

https://universumhub.com/demo/other/real-time-laravel-ratchet-websocket-chat-application/ and,this,have,laravel chat app,laravel chat application,laravel chat application with websocket,laravel chat script,laravel websockets,real time chat application in laravel,real time chat laravel

Post a Comment

0 Comments