Build an anonymous chat app in Laravel
A basic understanding of Laravel and Vue.js is needed to follow this tutorial.
The ability to socialize with other users has been an essential feature of apps and websites for many years now. Having an anonymous public chat application where we can communicate within a group, put forth our opinions without the fear of leaking our identity could be a great boon to many users.
Today, we will create a realtime Public Anonymous Group Chat App using Laravel and Pusher. With the release of Echo, Laravel has provided an out of the box solution for implementing a realtime chat application using event broadcasting. It is quite simple to get started in a matter of few minutes.
Setup an app on Pusher
We need to sign up with Pusher and create a new app.
Install Laravel, Pusher SDK and Echo
First, we will grab a fresh copy of Laravel:
laravel new public-anonymous-chat-laravel-pusher
This will install the latest version of the Laravel framework and download the necessary dependencies. Next, we will install the Pusher PHP SDK using Composer:
composer require pusher/pusher-php-server
Next, we will install the JavaScript dependencies:
npm install
Now, we need to install two JavaScript libraries necessary for realtime event broadcasting: Laravel Echo and Pusher JS
npm install --save laravel-echo pusher-js
Configuration
First, we need to set the APP_ID
, APP_KEY
, APP_SECRET
and APP_CLUSTER
in the environment file. We can get these details in our Pusher app dashboard:
# .env
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=your-pusher-app-id
PUSHER_APP_KEY=your-pusher-app-key
PUSHER_APP_SECRET=your-pusher-app-secret
PUSHER_APP_CLUSTER=your-pusher-app-cluster
Next, we need to create a fresh Echo instance in our applications’s JavaScript. We can do this at the bottom of our resources/assets/js/bootstrap.js
file:
import Echo from "laravel-echo"
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your-pusher-app-key',
cluster: 'ap2',
encrypted: true
});
Our application
We will implement a feature wherein a user can anonymously chat with other users. The core feature is to let the users chat without revealing their identity. It being a public chat room, any user visiting the page would be able to chat with other users without the need of any authentication.
Migrations
Next, we need a conversations
table to record all the messages sent by a user. Let us create a model and migration:
php artisan make:model Conversation -m
The conversations
table would require the following fields:
- A field to store body of each message
- A field to store a random anonymous name for the user
Below is our migration file for the conversations
table:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateConversationsTable extends Migration
{
public function up()
{
Schema::create('conversations', function (Blueprint $table) {
$table->increments('id');
$table->text('message');
$table->string('user');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('conversations');
}
}
Recording anonymous messages
To record messages anonymously, we need to generate and store a random username for each message. First, we will create a ConversationController
:
php artisan make:controller ConversationController
Next, we will record each message entry into a database. A random username will be assigned to the message from an array of anonymous usernames.
# routes/api.php
Route::post('conversations/store', 'ConversationController@store');
# ConversationController.php
public function store()
{
$random_usernames = [
'Anonymous',
'Someone',
'Some Girl',
'Some Boy',
'Mr. X',
'Mr. Y',
'Mr. ABC',
'Ms. A',
'Ms. B',
'Ms. C',
];
$conversation = Conversation::create([
'message' => request('message'),
'user' => $random_usernames[array_rand($random_usernames)],
]);
}
Now, a random username from the array will be assigned to each message. Let us create a conversation and check:
>>> Conversation::all();
=> Illuminate\Database\Eloquent\Collection {#687
all: [
App\Conversation {#688
id: 1,
message: "Some comment",
user: "Anonymous",
created_at: "2017-02-28 12:09:38",
updated_at: "2017-02-28 12:09:38",
},
App\Conversation {#689
id: 2,
message: "Another Comment",
user: "Some Girl",
created_at: "2017-02-28 12:09:43",
updated_at: "2017-02-28 12:09:43",
},
],
}
As we can see, a random username is assigned to both the comments in the above results.
Broadcasting Messages
Whenever a new message is recorded, we need to fire an event which would be broadcast over Pusher. For broadcasting an event, it should implement the ShouldBroadcast
interface. Let us first create the NewMessage
event:
php artisan make:event NewMessage
broadcastOn method
The event should implement a broadcastOn
method. This method should return the channels to which the event will be broadcast.
Our application is publicly available to anyone. Anyone can join and chat anonymously. We will not have any authorization for users to listen or send messages. Hence, we will simply use the public Channel
:
namespace App\Events;
use App\Conversation;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class NewMessage implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $conversation;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Conversation $conversation)
{
$this->conversation = $conversation;
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new Channel('public-chat');
}
}
Now, we need to start our queue to actually listen for jobs and broadcast any events that are recorded. We can use the database queue listener on our local environment:
php artisan queue:listen
Next, we need to broadcast this event to other users on the same channel. Let us use the broadcast
helper provided by Laravel to fire the event whenever a new message is recorded:
# ConversationController.php
public function store()
{
$random_usernames = [
'Anonymous',
'Someone',
'Some Girl',
'Some Boy',
'Mr. X',
'Mr. Y',
'Mr. ABC',
'Ms. A',
'Ms. B',
'Ms. C',
];
$conversation = Conversation::create([
'message' => request('message'),
'user' => $random_usernames[array_rand($random_usernames)],
]);
broadcast(new NewMessage($conversation))->toOthers();
}
Listening to new messages
Installation and configuration of Laravel Echo is a must before we can start listening to new messages. We have covered the process in detail in the above section of this article. Please go through it if you might have skipped it.
Being a public anonymous app, we can listen to new messages on a public channel using Echo.channel(channel)
:
listen() {
Echo.channel('public-chat')
.listen('NewMessage', (e) => {
this.conversations.push(e.conversation);
});
}
Now, whenever a new message is recorded, it is broadcast over Pusher. Next, we listen to that channel and push the new conversations to our conversations array in our Vue component.
Below is the JavaScript part of our Example component written using Vue.js
<script>
export default {
data() {
return {
conversations: [],
message: '',
}
},
mounted() {
this.getConversations();
this.listen();
},
methods: {
store() {
axios.post('/api/conversations/store', {
message: this.message
})
.then((response) => {
this.message = '';
this.conversations.push(response.data);
});
},
getConversations() {
axios.get('/api/conversations', {})
.then((response) => {
this.conversations = response.data;
});
},
listen() {
Echo.channel('public-chat')
.listen('NewMessage', (e) => {
this.conversations.push(e.conversation);
});
}
}
}
</script>
Below is the demonstration of our functionality:
Conclusion
In this article, we have demonstrated how to build an anonymous chat app with Laravel and Vue.js. We have covered the configuration options necessary to get started, and the examples above should help you fill in the gaps and give an overview of some of the other configuration options available to you.
15 March 2017
by Viraj Khatavkar