Implement online presence in a Laravel application
You will need the Laravel CLI installed on your machine. This tutorial uses Laravel 5.7. You will also need SQLite, and a basic knowledge of Laravel and PHP.
When using certain applications, it is usually expected that the current user is able to see all other users currently using the service alongside them. For instance, Dropbox Paper shows all the users that are currently viewing a document. This is very useful and it helps stop users feeling like they are alone on your application.
In this tutorial, we are going to see how you can add online presence reporting to a Laravel application. To showcase this, we will be building an application where users can log in and leave quick updates on anything they want. Each online user will be able to see the list of logged in users.
Here is the finished application in action:
Prerequisites
Before we get started, you need to have the following prerequisites:
- Laravel CLI installed on your machine. Installation guide.
- Node.js installed on your machine. Download the latest stable version here.
- SQLite (v3.x or later) installed on your machine.
- A Pusher account. Create one here.
- Basic PHP/Laravel knowledge.
- Basic CLI knowledge.
If you have the listed requirements, we can continue.
Setting up your Laravel project
The first thing we want to do is create a new Laravel project. To create a new Laravel project, run the following command in your terminal:
$ laravel new updaytes # where "updaytes" is the name of the project
This will create a new Laravel project that we can start working with. When the installation is complete, we will start installing the JavaScript dependencies using NPM.
Installing JavaScript dependencies
Open the package.json
file that comes with your Laravel installation and replace the contents with the following code:
{
"private": true,
"scripts": {
"dev": "npm run development",
"development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "npm run development -- --watch",
"watch-poll": "npm run watch -- --watch-poll",
"hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
},
"devDependencies": {
"axios": "^0.18.0",
"bootstrap": "^4.0.0",
"cross-env": "^5.1",
"jquery": "^3.2",
"laravel-mix": "^2.0",
"lodash": "^4.17.5",
"popper.js": "^1.12",
"vue": "^2.5.7"
},
"dependencies": {
"laravel-echo": "^1.4.0",
"pusher-js": "^4.3.1"
}
}
In your terminal, cd
to the root of your project and run the following command to install the JavaScript dependencies:
$ npm install
After installation is complete, open the webpack.mix.js
file and replace the contents with the following:
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/signin.scss', 'public/css')
.sass('resources/sass/app.scss', 'public/css')
.sass('resources/sass/updates.scss', 'public/css');
Above, we have added two new Sass files, signin.scss
and updates.scss
. In these files, we will be adding specific CSS for the sign in page and the updates page. Create these files in the resources/sass
directory and leave them empty.
Next, run the command below to build the assets:
$ npm run watch
The
watch
script keeps the command line occupied. It automatically watches for changes to your assets and builds automatically when it detects changes. This is better than running thebuild
script every time you make changes.
Setting up the database
For this tutorial, we will be using an SQLite database. It is easy to set up and is a good database engine for small projects. If you are building bigger projects though, you should use MySQL.
Create a new file named database.sqlite
in the database
directory and leave it empty. Next, open the .env
file in the root of your project and replace the following keys:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
With
DB_CONNECTION=sqlite
DB_DATABASE=/full/path/to/database.sqlite
Next, let’s add some classes that will help us manage our database and also seed the table with sample data. In your terminal, run the following command:
$ php artisan make:model Update -mc
As seen from the screenshot, this command generates a model, migration, and a controller. Before we start updating any of those, let’s also generate a model factory. Run the command below to generate a model factory:
$ php artisan make:factory UpdateFactory
Finally, let’s generate a database seeder. Seeders are used to add dummy data to the database and should not be used in production. Run the command below to generate a database seeder:
$ php artisan make:seed UsersTableSeeder
Now, let’s start updating the classes generated by the commands above. First, we will start with the migrations. Open the *_create_users_table.php
migration in the database/migrations
directory and replace the up
method with the following:
// File: database/migrations/*_create_users_table.php
// [...]
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('avatar')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
// [...]
The actual change we have from the previous code is the introduction of the avatar
field. We will use this field to store URL to the avatar of the user.
Next, open the *_create_updates_table.php
file in the database/migrations
directory and replace the up
method with the following:
// File: database/migrations/*_create_updates_table.php
// [...]
public function up()
{
Schema::create('updates', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->string('text', 280);
$table->timestamps();
});
}
// [...]
Above, we have the migration for the updates
table. It has the user_id
field which it’ll store the user ID of the user that made the update, and the text
field that stores the update made.
Now that we have defined the table structure using our migration files, let’s update the model for our tables.
Open the User.php
file in the app
directory and replace the class definition with the following code:
// File: ./app/User.php
// [...]
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'avatar',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Update model relationship
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function updates()
{
return $this->hasMany(Update::class);
}
}
The changes above are:
- We added the
avatar
field to thefillable
array. - We added the
updates
method, which is for the relationship between theUser
and theUpdate
. In this case, a user can have many updates, but an update can only belong to a user.
Next, open the Update.php
file in the app
directory and replace the class definition with the following:
// File: ./app/Update.php
// [...]
class Update extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_id', 'text'
];
/**
* User model relationship
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
Above, we have a typical Laravel model. The user
method is the relationship link from the Update
model to the User
model.
Now that we have the models, let’s update the model factories. Open the UserFactory.php
file in the database/factories
directory and replace it with the following code:
// File: ./database/factories/UserFactory.php
<?php
use Faker\Generator as Faker;
$factory->define(App\User::class, function (Faker $faker) {
$number = rand(10, 46);
$gender = rand(0, 1) ? 'men' : 'women';
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'avatar' => "https://randomuser.me/api/portraits/${gender}/{$number}.jpg",
'remember_token' => str_random(10),
];
});
Above, we have a model factory. When the factory is called to generate a user, the callback above is called and it returns a unique array of fields to be used when creating the sample user. The factory uses the Faker library for this. For the avatar, we are using a photo from the randomuser.me website.
Next, open the UpdateFactory.php
file in the database/factories
directory and replace the contents with the following code:
// File: ./database/factories/UpdateFactory.php
<?php
use Faker\Generator as Faker;
$factory->define(App\Update::class, function (Faker $faker) {
return [
'text' => $faker->sentence()
];
});
The factory essentially does the same as the previous factory, only for the Update
model.
Next, open the UsersTableSeeder.php
file in the database/seeds
directory and replace the run
method with the following:
// File: ./database/seeds/UsersTableSeeder.php
// [...]
public function run()
{
factory(App\User::class, 10)->create()->each(function ($user) {
$user->updates()->save(factory(App\Update::class)->make());
});
}
// [...]
Above, we have added the logic for the seeder. It will generate ten users using the UserFactory
, and for each of the users, it will generate an update using the UpdateFactory
. So basically, when the seeder is run, we will have ten dummy users with ten dummy posts.
Open the DatabaseSeeder.php
file in the database/seeds
directory and uncomment the line below:
$this->call(UsersTableSeeder::class);
With this, we are ready to run our migration and seed the database with sample data. Run the command below to do this:
$ php artisan migrate:fresh --seed
You can always run the command above to clear changes to the database. It will delete all the tables and run the migration and seed command from scratch.
Building our application
Now we are done with the database set up. Let’s start building the application.
Creating the login page
First, let’s add a login page. We will be using the /
route as the login page and we will not need the artisan make:auth
command that comes default with Laravel.
First, open the web.php
file in the routes
directory and replace the contents with the following code:
// File: ./routes/web.php
<?php
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
Route::post('/', 'Auth\LoginController@login');
Route::view('/', 'signin')->middleware('guest')->name('login');
Above, we have defined three routes:
GET /logout
- this will log a user out of the application. It uses theLoginController
that comes default with Laravel. We don’t need to do anything more.POST /
- this will handle logging in. It also uses theLoginController
and we do not need to do anything but send aPOST
request to it with theemail
andpassword
field.GET /
- this will display the login page. It uses aguest
middleware that comes with Laravel by default. This will redirect all logged in users away from the page to the dashboard.
Next, let’s create the signin page. In the resources/views
directory, create a new file named signin.blade.php
and paste the following code:
<!-- File: ./resources/views/signin.blade.php -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Updaytes | Sign in</title>
<meta content="{{ csrf_token() }}" name="csrf-token">
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<link rel="stylesheet" href="{{ asset('css/signin.css') }}">
</head>
<body class="text-center">
<form class="form-signin" method="POST" action="{{ route('login') }}">
@csrf
<h3 class="h3 mb-3 font-weight-normal">Please sign in</h3>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" name="email" class="form-control" placeholder="Email address" value="{{ old('email') }}" required>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block signin-btn" type="submit">
Sign in
</button>
</form>
</body>
</html>
Above, we have the HTML for the sign in page. In the head
it is referencing the signin.css
file, which at this point is empty. So let’s add the style for this page.
Open the resources/sass/signin.scss
file and paste the following code:
// File: ./resources/sass/signin.scss
html, body {
height: 100%;
}
body {
display: -ms-flexbox;
display: flex;
-ms-flex-align: center;
align-items: center;
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
.form-signin {
width: 100%;
max-width: 330px;
padding: 15px;
margin: auto;
}
.form-signin .checkbox {
font-weight: 400;
}
.form-signin .form-control {
position: relative;
box-sizing: border-box;
height: auto;
padding: 10px;
font-size: 16px;
}
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type='email'] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type='password'] {
border-radius: 0;
}
.form-signin .signin-btn {
font-weight: bold;
font-size: 15px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
Above, we have the style for the sign in page. Because we have the npm run watch
command still running, the Sass file will be automatically compiled.
Run the command below in a terminal window to start the Artisan server:
$ php artisan serve
In your browser, visit the URL http://localhost:8000/ and you should see the login screen. Great.
Now quit the serve command by pressing ctrl + c on your keyboard. Let’s create the updates page.
Creating the updates page
Before we start creating the pages for the updates view, let’s add some routes. Open the web.php
file in the routes
directory and add the following code:
// [...]
Route::get('home', 'UpdateController@index')->name('home');
Route::get('/updates', 'UpdateController@list');
Route::post('/updates', 'UpdateController@create');
Route::get('/updates/suggestions', 'UpdateController@userSuggestions');
// [...]
Above, we have four routes:
GET /home
- this will be the page where all the updates will be displayed.GET /updates
- this will be an API endpoint that we will load from the/home
route. It will return a JSON response of all the updates.POST /updates
- this will be an API endpoint that we will use to add new updates. It will return a JSON response of the new update.GET /updates/suggestions
- this will be an API endpoint that will return a JSON response of random users. Not really important, it’s just for aesthetics.
Now that we have the routes, let’s update the UpdateController
. Open the UpdateController.php
file in the app/Http/Controllers
directory and replace the contents with the following:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Update;
use Illuminate\Http\Request;
use App\Events\UpdateCreated;
class UpdateController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('updates');
}
public function create(Request $request)
{
$data = $request->validate(['text' => 'required|min:1|max:280|string']);
$update = auth()->user()->updates()->save(new Update($data))->load('user');
broadcast(new UpdateCreated($update))->toOthers();
return response()->json($update);
}
public function list()
{
return response()->json(Update::latest()->with('user')->limit(15)->get());
}
public function userSuggestions()
{
$user = auth()->user();
return response()->json(
User::where('id', '!=', $user->id)->inRandomOrder()->limit(5)->get()
);
}
}
Above, we have a few methods defined:
__construct
- in here we add theauth
middleware so that only authenticated users can visit any of the pages in this controller.index
- the updates page.create
- creates a new update, sends a broadcast to Pusher, and returns a JSON response.list
- returns a JSON response with the latest updates.userSuggestions
- returns a JSON response with random users.
To create the event we are broadcasting in the create
method, run the following command below:
$ php artisan make:event UpdateCreated
For now, we will leave the generated class and move on.
Let’s add the HTML and style for the updates page. Create a new updates.blade.php
file in the resources/views
directory and paste the following:
<!-- File: ./resources/views/updates.blade.php -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Updytes | Home</title>
<meta content="{{ csrf_token() }}" name="csrf-token">
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<link href="{{ asset('css/updates.css') }}" rel="stylesheet">
</head>
<body class="bg-light updates">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand mr-auto mr-lg-0" href="#">UPDAYTES</a>
<div class="navbar-collapse offcanvas-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="{{ route('logout') }}" onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
{{ __('Logout') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
@csrf
</form>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<div id="app">
<div class="nav-scroller bg-white shadow-sm clearfix">
<OnlineList :me='@json(auth()->user()->toArray())'></OnlineList>
</div>
<main role="main" class="container">
<div class="d-flex align-items-center p-3 my-3 text-white-50 bg-purple rounded shadow-sm">
<div class="lh-100">
<h6 class="mb-0 text-white lh-100">Bootstrap Forum</h6>
<small>Updates on the development of the community</small>
</div>
</div>
<Updates></Updates>
<Suggestions></Suggestions>
</main>
</div>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
Above, we have the HTML for the updates page. There are a few things to note in the markup above:
- It references the
updates.css
style, which we have not yet created. - It has three Vue components referenced,
OnlineList
,Updates
, andSuggestions
, which we have not created. - It includes the
js/app.js
file which will contain our bundled JavaScript.
Let’s add some styling to the page. Open the updates.scss
file in the resources/sass
directory and paste the following:
// File: ./resources/sass/updates.scss
.updates {
.bg-purple {
background-color: #6f42c1;
}
.size-32 {
width: 32px;
height: 32px;
}
.nav-scroller .nav-link {
line-height: 32px;
display: inline-block;
margin-right: -9px;
float: right;
}
.squished {
padding-left: 0;
padding-right: 0;
&:first-child,
&:last-child {
margin-right: 15px;
}
}
.avatar {
border-radius: 50%;
text-indent: 1000px;
border-radius: 50%;
height: 34px;
line-height: 34px;
width: 34px;
border: 2px solid #fff;
}
}
Above, we have the style for the updates page. Because we have the npm run watch
command still running, the Sass file will be automatically compiled.
Next, let’s create the Vue components referenced in the updates page. Create the following files in the resources/js/components
directory:
Updates.vue
Suggestions.vue
OnlineList.vue
Next, open the resources/js/app.js
file and replace the contents with the following:
require('./bootstrap');
require('axios');
window.Vue = require('vue');
Vue.component('updates', require('./components/Updates.vue'));
Vue.component('onlinelist', require('./components/OnlineList.vue'));
Vue.component('suggestions', require('./components/Suggestions.vue'));
const app = new Vue({
el: '#app'
});
Above, we imported Axios, which we will use for HTTP requests, we also registered the Vue components we created earlier.
Let’s update the contents of the Vue components. Open the Updates.vue
file and paste the following code into it:
<!-- File: ./resources/js/components/Updates.vue -->
<template>
<div class="my-3 p-3 bg-white rounded shadow-sm">
<h6 class="border-bottom border-gray pb-2 mb-0">Recent updates</h6>
<div class="media text-muted pt-3" v-if="updates.length == 0">
Loading updates...
</div>
<div class="media text-muted pt-3 pb-3 border-bottom border-grey" v-else>
<form class="form-inline" v-on:submit.prevent="addUpdate">
<div class="form-group mr-2">
<input type="text" class="form-control" v-model="update" placeholder="What's happening?">
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>
<div class="media text-muted pt-3" v-for="update in updates" :key="update.id">
<img :src="update.user.avatar" class="size-32 mr-2 rounded">
<p class="media-body pb-3 mb-0 small lh-125 border-bottom border-gray">
<strong class="d-block text-gray-dark">
{{ update.user.name }}
</strong>
{{ update.text }}
</p>
</div>
</div>
</template>
<script>
export default {
name: 'Updates',
data() {
return {
update: '',
updates: [],
}
},
mounted () {
axios.get('/updates').then(res => (this.updates = res.data))
},
methods: {
addUpdate () {
if (this.update.trim() !== '') {
axios.post('/updates', {text: this.update}).then(res => {
this.update = ''
this.updates.unshift(res.data)
})
}
}
}
}
</script>
Above, the component is divided into template
and script
. The template
contains the HTML for the component and the script
contains the JavaScript.
In the script
we load the updates in the mounted
method. In the template
we loop through all the updates
and display each. We also have a form that we can use to post a new update. When submitted, this form calls the addUpdate
function in the methods
property.
Next, open the resources/js/components/Suggestions.vue
and paste the following code:
<!-- File: ./resources/js/components/Suggestions.vue -->
<template>
<div class="my-3 p-3 bg-white rounded shadow-sm">
<h6 class="border-bottom border-gray pb-2 mb-0">Suggestions</h6>
<div class="media text-muted pt-3" v-if="users.length == 0">
Loading users...
</div>
<div class="media text-muted pt-3" v-for="user in users" :key="user.id">
<img :src="user.avatar" :alt="user.name" class="size-32 mr-2 rounded">
<div class="media-body pb-3 mb-0 small lh-125 border-bottom border-gray">
<div class="d-flex justify-content-between align-items-center w-100">
<strong class="text-gray-dark">{{ user.name }}</strong>
<a href="#">Follow</a>
</div>
<span class="d-block">Follow my updates</span>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'Suggestions',
data() {
return {
users: []
}
},
mounted () {
axios.get('/updates/suggestions').then(res => (this.users = res.data))
}
}
</script>
Just like the Updates
component, we have the template
and script
tag. The script
loads the suggested users and the template
loops over the users
and displays them.
Finally, open the file resources/js/components/OnlineList.vue
and paste the following code:
<!-- File: ./resources/js/components/OnlineList.vue -->
<template>
<ul class="nav float-right">
<li class="nav-link squished">Online Users</li>
<li class="nav-link squished" href="#" v-for="user in users" :key="user.id">
<img class="avatar" :src="user.avatar" :alt="user.name">
</li>
</ul>
</template>
<script>
export default {
name: 'OnlineList',
props: ['me'],
data () {
return {
users: []
}
},
mounted () {
this.users.push(this.me)
}
}
</script>
Like the components before it, the OnlineList
component has the template
that loops through the data and the script
that loads the data.
We have not yet implemented the who’s online feature so, in the mounted
method, we just add the current user as the only online user. We will add the presence and realtime feature in the next section.
Adding the realtime and presence feature
Let’s start from the Laravel PHP side. We will first activate the broadcasting feature, then we will update the configuration in our .env
file, after which we will update the event file we created earlier.
Open the config/app.php
file and uncomment the BroadcastServiceProvider
line:
App\Providers\BroadcastServiceProvider::class,
Next, open the .env
file and change the BROADCAST_DRIVER
from log
to pusher
. Finally, in the same file, update the keys below with the keys from your Pusher dashboard.
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=
Next, open the app/Events/UpdateCreated.php
file and replace the contents with the following:
// File: app/Events/UpdateCreated.php
<?php
namespace App\Events;
use App\Update;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class UpdateCreated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $update;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Update $update)
{
$this->update = $update;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('updates');
}
}
Above, we have a Laravel event class. Notably, we have the broadcastsOn
method which defines the channel we want to broadcast this event on. In this case, we are using a private channel called updates
.
Note that we are implementing the
ShouldBroadcast
interface. If we don’t, the event will not be broadcasted to our Pusher instance.
Next, open the routes/channels.php
file and replace the contents with the following code:
// File: ./routes/channel.php
<?php
Broadcast::channel('updates', function ($user) {
return auth()->check();
});
Broadcast::channel('online', function ($user) {
if (auth()->check()) {
return $user->toArray();
}
});
Because our channels are private, presence is private by default, we have to define the authentication logic. The first one checks if the current user is logged in. Only logged in users can listen in on the updates
channel.
The second checks to see if the user can listen on the online
presence channel. Unlike the first, the presence channel does not return a boolean. It returns details of the user if the user is authorized.
One last thing we need to do is pull in the Pusher PHP SDK. Run the following command in your terminal to do this:
$ composer require pusher/pusher-php-server
Now, let’s go over to the JavaScript side. Open the resources/js/bootstrap.js
file and uncomment the following lines at the bottom of the file:
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true
});
This will make Laravel Echo available to us. We will use this library to interact with Pusher.
Next, open the Updates.vue
file and update the mounted
method as seen below:
// [...]
mounted () {
axios.get('/updates').then(res => (this.updates = res.data))
Echo.private('updates')
.listen('UpdateCreated', data => this.updates.unshift(data.update))
}
// [...]
Above, we are using Laravel Echo to listen for the UpdateCreated
event on the updates
channel. Every time a new update is added, the event above will be triggered and the callback inside the listen
method will be invoked.
In the callback, we add the update
to the top of the updates
array. Because Vue is reactive, the data will be updated instantly on the UI.
Next, open the OnlineList.vue
file and update the mounted
method as seen below:
// [...]
mounted () {
// [...]
Echo.join('online')
.here(users => (this.users = users))
.joining(user => this.users.push(user))
.leaving(user => (this.users = this.users.filter(u => (u.id !== user.id))))
}
// [...]
Above we have the magic that handles online presence. We use Echo to join
the online
presence channel. Then the methods chained are:
here
- this returns all the users currently in this presence channel. In the callback, we set theusers
array to the response.joining
- this is called when a new user comes online. In the callback, we simplypush
the new user to theusers
array.leaving
- this is called when a user disconnects or goes offline. In the callback, we filter out the user that disconnected from theusers
array.
That’s all. Now let’s test our application to see it in action.
Testing the application
To test the application, we need two accounts that we can log into. You can check the users
table in the SQLite database but there is an easier way to get the users.
In your terminal, run the command below:
$ php artisan tinker
Laravel Artisan’s tinker is a repl (read-eval-print loop). A repl translates to
read-eval-print-loop
, and it is an interactive language shell. It takes in a single user input, evaluates it, and returns the result to the user. - Scotch.io
In the interactive shell, run the following command:
>>> App\User::inRandomOrder()->limit(2)->get()->implode('email', " ")
This will give us the emails of two random users.
We can use these email addresses to log in as the demo users. The password is secret for all the demo users.
Run the command below to exit tinker
(you can also press ctrl + c on your keyboard):
>>> exit
Now run the command below to start your PHP server:
$ php artisan serve
Now, open two different browsers. In both, visit the URL http://localhost:8000 and log in as both users on the different browsers. You should see the application in action like this:
Conclusion
In this tutorial, we have seen how easy it is to work with presence channels on a Laravel application.
The source code is available on GitHub.
9 October 2018
by Neo Ighodaro