Real-time Chat App using Laravel Pusher and Jquery

By:

ITS

Category:

Laravel development

Introduction
Pusher is a hosted service that enables to use real-time data in web and mobile applications. Laravel Pusher has many features that make it a popular choice for building real-time applications. Here are some of the key features of Pusher:

  • Real-time messaging: Pusher enables real-time messaging between clients and servers, allowing developers to build real-time applications that update in real-time.
  • Channels: Pusher uses channels to manage data communication between clients and servers. Channels are used to group data by type, making it easier for developers to manage their data.
  • Webhooks: Pusher provides webhooks that receive real-time notifications when certain events occur. This can be useful for triggering actions in your real-time chat application.
  • Authentication: Pusher provides authentication mechanisms that enable developers to secure their real-time applications.
  • Presence: Pusher’s presence channels provide developers with a way to track the status of users in real-time applications. Presence channels help build features such as user presence, user lists, and online/offline status.

Types of Laravel Pusher Channels

Pusher provides four types of channels for developers to use in their real-time applications:
  • Public Channels: These channels are open to everyone; any user can subscribe to them without any authentication. Public channels are suitable for broadcasting events that everyone can see.
  • Private Channels: These channels are only accessible to authenticated users. You can use private channels to send sensitive information only specific users should see.
  • Presence Channels: These channels are similar to private channels but also provide information about who is currently subscribed to the channel. Presence channels are useful for building real-time chat applications, online collaboration tools, and multiplayer games.
  • Encrypted Channels: These channels provide end-to-end encryption for messages sent between clients and servers. Encrypted channels are useful for applications that deal with sensitive data or require high security.
Developers can choose the appropriate type of channel based on their application’s use case and security requirements. Pusher’s channel types offer a range of options to suit various needs and enable developers to build real-time applications quickly and easily.

How to Create Pusher Account

1. Go to the Pusher website at Pusher.
2. Click on the “Sign up” button in the top right corner of the page.
3. Fill out the registration form with your name, email address, and password.
4. Click on the “Create account” button.
5. You will receive a confirmation email from Pusher. Click on the link in the email to verify your email address and activate your account.
6. Once your account is activated, you can log in to the Pusher dashboard and start using Pusher’s real-time communication infrastructure to build your applications.

How to Create an App in Pusher Laravel

1. Log in to your Pusher account and go to the dashboard.
2. Click on the “Create new app” button.
3. Fill out the form with your app’s name, description, and the technology you’ll be using (e.g., JavaScript, React, iOS, etc.).
4. Select the cluster you want to use for your app (Pusher provides different clusters located in different regions to optimize performance for your users).
5. Click on the “Create app” button to create your app.

Once you have created your app, Pusher will provide you with an App ID, API Key, and API Secret. You will need these credentials to use chat Pusher APIs and libraries in your application. You can find these credentials in the app dashboard under the “App Keys” tab.

After creating your app, you can configure the settings and features you want to use in your application. For example, you can create channels, configure webhooks, set up authentication, and more. Pusher’s documentation provides detailed guides and examples on how to use Pusher’s features in your application.

Example Of Chat App with Laravel Pusher and JQuery

In this Laravel Pusher tutorial, we will see how to create a real-time chat application using Pusher in Laravel.

Step 1: Install Package

composer require pusher/pusher-php-server

Configure app credentials to your .env file

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=
Don’t forget to clear cache : php artisan config:clear

Step 2: Create Route

Route::post(‘pusher/send-message’, ‘pusherController@sendMessage’)->name(‘pusher.sendmessage’);

Step 3: Send a message using Laravel Pusher and Jquery

Jquery:

var message = ‘Hello, This is my first real time message’;
$.ajax({
type: ‘POST’,
cache: false,
dataType: ‘json’,
url: ‘{{route(“pusher.sendmessage”)}}’,
contentType: false,
processData: false,
data: {message : message},
headers: {
‘X-CSRF-TOKEN’: $(‘meta[name=”csrf-token”]’).attr(‘content’)
},
success: function (result) {
if(result.response_code == 1){
alert(“Message has been sent”);
}else{
alert(“Fail to send message”);
}
},
error: function(){
alert(“Something went wrong please try again later”);
}
});

Laravel:

use Pusher\Pusher;
use Validator;
class pusherController extends Controller{
public function sendMessage(Request $request) {
$return_data[‘response_code’] = 0;
$return_data[‘message’] = ‘Something went wrong, Please try again later.’;

$rules = [‘message’ => ‘required’];
$messages = [‘message.required’ => ‘Please enter message to communicate.’];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
$message = implode(“
“, $validator->messages()->all());
$return_data[‘message’] = $message;
return $return_data;
}

try {
$options = [
‘cluster’ => env(‘PUSHER_APP_CLUSTER’),
‘useTLS’ => true
];

$pusher = new Pusher(
env(‘PUSHER_APP_KEY’),
env(‘PUSHER_APP_SECRET’),
env(‘PUSHER_APP_ID’),
$options
);

$response = $pusher->trigger(‘my-chat-channel’, ‘my-new-message-event’, [‘message’ => $request->message]);
if($response){
$return_data[‘response_code’] = 1;
$return_data[‘message’] = ‘Success.’;
}
} catch (\Exception $e) {
$return_data[‘message’] = $e->getMessage();
}
return $return_data;
}
}

Step 6: Implement Login Logic

/**
* @OA\Post(
* path=”/api/login”,
* summary=”Authenticate user and generate JWT token”,
* @OA\Parameter(
* name=”email”,
* in=”query”,
* description=”User’s email”,
* required=true,
* @OA\Schema(type=”string”)
* ),
* @OA\Parameter(
* name=”password”,
* in=”query”,
* description=”User’s password”,
* required=true,
* @OA\Schema(type=”string”)
* ),
* @OA\Response(response=”200″, description=”Login successful”),
* @OA\Response(response=”401″, description=”Invalid credentials”)
* )
*/
public function login(Request $request)
{
$credentials = $request->only(’email’, ‘password’);
if (Auth::attempt($credentials)) {
$token = Auth::user()->createToken(‘api_token’)->plainTextToken;
return response()->json([‘token’ => $token], 200);
}
return response()->json([‘error’ => ‘Invalid credentials’], 401);
}

Conclusion

Pusher is a powerful platform that enables developers to build real-time web and mobile applications quickly and easily. Its range of features and intuitive chat Pusher API make it a popular choice for developers looking to build real-time applications. Whether you’re building a real-time chat application, a collaborative tool, or a multiplayer game, Laravel Pusher provides the infrastructure and tools you need to make it happen. Leverage Our Laravel development services can help you integrate Pusher and build interactive, collaborative, and high-performance applications. Contact us today to know more.
We are trusted by over 650+ clients.
Join them by using our services and grow your business.

Get Started

SiteLogo
“At Inspire Techno Solution , our mission is to continuously innovate the best ways to train the next generation of developers and to transform the way tech education is delivered.”

Find a Career with us

Related Blogs

Real-time Chat App using Laravel Pusher and Jquery | Inspire Techno Solution

Real-time Chat App using Laravel Pusher and Jquery

Pusher is a cloud-based platform enabling developers to quickly create real-time web and mobile applications.
Laravel Octane to Scale your Application in 2024 | Inspire Techno Solution

Laravel Octane to Scale your Application in 2024

Laravel has gained a lot of attention in recent years, though it has been a
Laravel Swagger Integration A Comprehensive Step-by-Step Guide | Inspire Techno Solution

Laravel Swagger Integration: A Comprehensive Step-by-Step Guide

This guide offers a comprehensive and easy-to-follow tutorial on Laravel Swagger Integration. Following the step-by-step