How to add pusher and post real time messages to another user account in Laravel
Configuring pusher in Laravel and making real time post
This tutorial seeks to get you started with the usage of pusher in Laravel. You will be learning how to configure pusher credentials and send message from one user account to another. If you would like to know why pusher is a good option for managing real time data you can visit: https://pusher.com/channels/features
Graphical representation of how pusher works
Lets get started
Step 1: Install Laravel 7
The first thing we need to do is get a clean Laravel application using the command below. Please open your terminal OR command prompt and run the command below:
composer create-project --prefer-dist laravel/laravel messenger
Step 2: Make auth
Laravel’s laravel/ui
package provides a quick way to scaffold all of the routes and views you need for authentication using a few simple commands:
composer require laravel/ui --devphp artisan ui vue --auth
Step 2: Install Pusher
If you are broadcasting your events over Pusher Channels, you should install the Pusher Channels PHP SDK using the Composer package manager: Run this below command.
composer require pusher/pusher-php-server
Step 3: Install Laravel Echo
Laravel Echo is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by Laravel. You may install Echo via the NPM package manager.
npm install --save laravel-echo pusher-js
After installing it, open config/app.php file and uncomment this following line.
config/app.php
App\Providers\BroadcastServiceProvider::class,
Now open config/broadcasting.php file and make this changes.
config/broadcasting.php
'default' => env('BROADCAST_DRIVER', 'pusher'),
Now we have to connect pusher with Laravel. So go to puhser and create a new app and paste this key to .env file like below. Make sure you have changed broadcast driver log to pusher.
.env
BROADCAST_DRIVER=pusherPUSHER_APP_ID=xxxxxxxx
PUSHER_APP_KEY=xxxxxxxxxxx
PUSHER_APP_SECRET=xxxxxxxxx
PUSHER_APP_CLUSTER=xxxx
Step 4: Setup Migration
To create our project migration for our message table, run below command
php artisan make:model Message -m
after doing it open your messages migration file and paste this following code.
Schema::create('messages', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->integer('user_id');
$table->timestamps();
});
Now run php artisan migrate to migrate our table.
php artisan migrate
Step 5: Setup Route
routes/web.php
Route::get('/message', 'MessageController@index')->name('message')->middleware('auth');
Route::post('/message', 'MessageController@createMessage')->middleware('auth');
Step 5: Setup Controller
Now open MessageController and paste this following code.
app/Https/Controller/MessageController.php
namespace App\Http\Controllers;use App\Message;
use App\Events\MessageCreated;
use Illuminate\Http\Request;class MessageController extends Controller
{
public function index()
{
return view('message.create');
}public function createMessage(Request $request)
{
$message = new Message;
$message->title = $request->title;
$message->user_id = $request->user_id;
$message->save(); // broadcast(new MessageCreated($message));
// event(new MessageCreated($message)); return response()->json([
'message' => 'New message created'
]);
}
}
Step 6: Create Event
Now we have to create our broadcasting event to fire our broadcasting channel. To do it run following command.
php artisan make:event MessageCreated
after running this command you will find this file inside app/Events/MessageCreated.php path. Open it and paste this code.
app/Events/MessageCreated.php
namespace App\Events;use App\Message;
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;class MessageCreated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels; public $message; public function __construct(Message $message)
{
$this->message = $message;
} public function broadcastOn()
{
return new PrivateChannel('message.created');
}
}
Now open Message model and paste this following code.
app/Message.php
namespace App;use App\Events\MessageCreated;
use Illuminate\Database\Eloquent\Model;class Message extends Model
{
protected $guarded = []; protected $dispatchesEvents = [ 'created' => MessageCreated::class,
];
}
Step 7: Install Vue dependency and edit configurations
Now, go inside the project folder and install the front end dependencies using the following command.
npm install
now open this followng file and paste this code. Make an asstes folder inside resources folder and copy js and sass folder inside it. Thats all. We need it to setup our laravel mix.
webpack.mix.js
const mix = require('laravel-mix');
mix.js('resources/assets/js/app.js', 'public/js/app.js')
.sass('resources/assets/sass/app.scss', 'public/css/app.css');
now create a vue component called MessageComponent to create our message and paste this code.
resources/assets/js/components/MessageComponent.vue
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Create new message</div> <div class="card-body">
<p id="success"></p>
<form @submit.prevent="addNewMessage">
<input type="text" name="title" v-model="newMessage">
<input type="submit" value="Submit">
</form>
</div>
</div>
</div>
</div>
</div>
</template><script>
export default {
data(){
return {
newMessage: ''
}
},
methods: {
addNewMessage(){ var userId = $('meta[name="userId"]').attr('content'); axios.message('/message',{title: this.newMessage, user_id:userId})
.then((response)=>{ $('#success').html(response.data.message) })
}
}
}
</script>
now open this file resources/assets/js/bootstrap.js and uncomment this following line of code.
resources/assets/js/bootstrap.js
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
});
now open app.js file and paste this followng code.
resources/assets/js/app.js
require('./bootstrap');window.Vue = require('vue');Vue.component('message-component', require('./components/MessageComponent.vue').default);const app = new Vue({
el: '#app',
created() {
Echo.private('message.created')
.listen('MessageCreated', (e) => {
alert(e.message.title + 'Has been published now');
console.log(e.message.title)
console.log("Loaded")
});
}
});
now open channels.php file to setup our private channel.
routes/channels.php
Broadcast::channel('message.created', function ($message) {
info("Load from channel");
return (int) auth()->user()->id != (int) $message->user_id;});
Step 7: Setup blade file
Now time to setup our blade file. open resources/layouts/app.php and paste this following code.
resources/views/layouts/app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="userId" content="{{ Auth::check() ? Auth::user()->id : '' }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<link href="{{ mix('css/app.css') }}" rel="stylesheet">
<title>Document</title>
</head>
<body>
<div id="app"> <div class="py-4">
@yield('content')
</div>
</div>
<script src="{{ mix('js/app.js') }}" defer></script>
</body>
</html>
Now open resources/views/message/create.blade.php file and paste this code.
resources/views/message/create.blade.php
@extends('layouts.app')@section('content') <message-component></message-component>
@endsection
Now everything is set to go. Now just we have to compile all our js files. so run below command.
npm run dev
//or
npm run watch
then visit this following url, then you will see a form to create message. Just create a message then you should see the real time message from Laravel Echo and Pusher.
URL
http://localhost:8000/message
Hint: create 2 user accounts and then run them in split screen to see the full effect when a message is sent from one user to the other.