Hi Artisan,
In this tutorial, i will guide you step by step how to use event broadcasting using pusher and laravel-echo-server in laravel 8 application. Laravel provide event broadcasting topic. event broadcast is a very interesting and it's also easy to implement with pusher specially.
Buti will give you step by step instruction of how to send real time notification with pusher using laravel Echo in laravel 8 application. In this tutorial i will create a new post, when a new post is created then our broadcast event will be happend.
Let's start our laravel broadcast tutorial example from scratch. Hope you will enjoy this laravel broadcasting tutorial.
You need to just follow few step to done this following thing. so let's follow bellow steps and done as real time notification with laravel.
Step 1: Install Laravel 8
First of all, we need to get fresh Laravel 8 version application using bellow command because we are going from scratch, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
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 --dev
php 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 "~4.0"
Step 3: Install Larave 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 in laravel 6 everything should be ok. 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=pusher
PUSHER_APP_ID=933362
PUSHER_APP_KEY=f18ead0fa8750c93afd7
PUSHER_APP_SECRET=7d8af7728ca7242f0607
PUSHER_APP_CLUSTER=mt1
Step 4: Setup Migration
To create our project migration for our post table, run below command
php artisan make:model Post -m
after doing it open your posts migration file and paste this following code.
Schema::create('posts', 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('/post', 'PostController@index')->name('post')->middleware('auth');
Route::post('/post', 'PostController@createPost')->middleware('auth');
Step 5: Setup Controller
Now open PostController and paste this following code.
app/Https/Controller/PostController.php
namespace App\Http\Controllers;
use App\Post;
use App\Events\PostCreated;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
return view('post.create');
}
public function createPost(Request $request)
{
$post = new Post;
$post->title = $request->title;
$post->user_id = $request->user_id;
$post->save();
// broadcast(new PostCreated($post));
// event(new PostCreated($post));
return response()->json([
'message' => 'New post 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 PostCreated
after running this command you will find this file inside app/Events/PostCreated.php path. Open it and paste this code.
app/Events/PostCreated.php
namespace App\Events;
use App\Post;
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 PostCreated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $post;
public function __construct(Post $post)
{
$this->post = $post;
}
public function broadcastOn()
{
return new PrivateChannel('post.created');
}
}
Now open Post model and paste this following code.
app/Post.php
namespace App;
use App\Events\PostCreated;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $guarded = [];
protected $dispatchesEvents = [
'created' => PostCreated::class,
];
}
Step 7: Install Vue dependency and edit configurations
Now, go inside the project folder and install the frontend 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.
Read also : Laravel Vue JS CRUD Example With File Upload and Pagination
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 PostComponent to create our post and paste this code.
resources/assets/js/components/PostComponent.vue
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('post-component', require('./components/PostComponent.vue').default);
const app = new Vue({
el: '#app',
created() {
Echo.private('post.created')
.listen('PostCreated', (e) => {
alert(e.post.title + 'Has been published now');
console.log(e.post.title)
console.log("Loaded")
});
}
});
now open channels.php file to setup our private channel.
routes/channels.php
Broadcast::channel('post.created', function ($post) {
info("Load from chanell");
return (int) auth()->user()->id != (int) $post->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
Now open resources/views/post/create.blade.php file and paste this code.
resources/views/post/create.blade.php
Now everything is set to go. Now just we have to compile our all javascript file. so run below command.
npm run dev
//or
npm run watch
then visit this following url, then you will see a form to create post. Just create a post then you should see the real time message from Laravel Echo and Pusher.
Hope you enjoy this tutorial and hope it will help you to learn Laravel Broadcasting event to create real time notification system.
#laravel #broadcasting #event-broadcasting #events #notification #laravel-6 #pusher