Học về Real Time Broadcasting với Laravel 8.x Vuejs and Pusher

24th Aug 2021
Table of contents

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.

Xem thêm về cài đặt Vue

>> Hướng dẫn học và cài đặt sử dụng Vue in your Laravel 8 app

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 6:  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 7:  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 8:  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

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Create new post</div>

                    <div class="card-body">
                        <p id="success"></p>
                        <form @submit.prevent="addNewPost">
                            <input type="text" name="title" v-model="newPost">
                            <input type="submit" value="Submit">
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        
        data(){
            return {
              newPost: ''
            }
        },
        methods: {
            addNewPost(){

                var userId = $('meta[name="userId"]').attr('content');

                axios.post('/post',{title: this.newPost, 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('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 9:  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/post/create.blade.php file and paste this code. 

resources/views/post/create.blade.php

@extends('layouts.app')

@section('content')

  <post-component></post-component>
           
@endsection

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.

http://localhost:8000/post

Hope you enjoy this tutorial and hope it will help you to learn Laravel Broadcasting event to create real time notification system.

Bạn thấy bài viết này như thế nào?
1 reaction

Add new comment

Image CAPTCHA
Enter the characters shown in the image.
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”

Related Articles

Mỗi kết nối cơ sở dữ liệu được định nghĩa trong một mảng, với tên kết nối là khóa của mảng

Eager Loading là một kỹ thuật tối ưu hóa truy vấn cơ sở dữ liệu trong Laravel, giúp tăng tốc độ truy vấn và giảm số lượng truy vấn cần thiết để lấy dữ liệu liên quan đến một bản ghi.

Để sử dụng Eager Loading với điều kiện trong Laravel, bạn có thể sử dụng phương thức whereHas hoặc orWhereHas trong Eloquent Builder.

E hiểu đơn giản vầy nha. auth() hay Auth trong laravel là những function global hay class, nó cũng chỉ là 1 thôi

Xin chào các bạn, tuần này mình sẽ viết một bài về cách xử lý Real Time(thời gian thực) với Laravel và Pusher