The issue with combining Laravel 5.4 event broadcasting and Vue.js has been a challenging obstacle to

Looking to set up a chat system using Laravel 5.4, Vue.js, and Pusher API with Echo. I have tried twice to establish communication with Pusher, but I haven't received any callbacks in my Vue component. I am working locally with MAPM.

I have installed the following packages:

composer require pusher/pusher-php-server
npm install --save laravel-echo pusher-js

In my Blade file, I have added:

<meta name="csrf-token" content="{{ csrf_token() }}">

In my bootstrap.js file, I uncommented Echo and added my Pusher key:

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'my-push-key'
});

My broadcasting configuration:

'default' => env('BROADCAST_DRIVER', 'null'),
    'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
             //
            ],
        ],

        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
        ],

        'log' => [
            'driver' => 'log',
        ],

        'null' => [
            'driver' => 'null',
        ],

    ],

My .env file:

BROADCAST_DRIVER=log
PUSHER_APP_ID=my id key
PUSHER_APP_KEY=my app key
PUSHER_APP_SECRET=my secret key

In my app.js:

const root = new Vue({
    el: '#root',

    data: {

        messages: []
    },

    methods: {
        addMessage(message){
            this.messages.push(message);

            axios.post('/messages', message).then(response => {

            });
        }
    },

    created() {

        axios.get('/messages').then(response => {
            this.messages = response.data;
        });


        Echo.join('chatroom')
            .here()
            .joining()
            .leaving()
            .listen('MessagePosted', (e) => {
                console.log(e);
        });
    }
});

My controller:

public function store(Request $request){

        $user = Auth::user();

        $message = $user->messages()->create([
            'message' => $request->message
        ]);


        event(new MessagePosted($message, $user));
        return ['status' => 'OK'];

    }

My event:

namespace App\Events;

use App\Message;
use App\User;
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 MessagePosted implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;


    public $message;
    public $user;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Message $message, User $user)
    {
        $this->message = $message;
        $this->user = $user;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PresenceChannel('chatroom');
    }
}

And my channel route:

Broadcast::channel('chatroom', function ($user) {
    return $user;
});

Answer №1

1) To begin, let's focus on your .env file

BROADCAST_DRIVER =pusher // instead of log

2) Update config/app.php

App\Providers\BroadcastServiceProvider::class, //Uncomment this line

3) Adjust settings in config/broadcasting.php

'pusher' => [
    'driver' => 'pusher',
    'key' => env('PUSHER_APP_KEY'),
    'secret' => env('PUSHER_APP_SECRET'),
    'app_id' => env('PUSHER_APP_ID'),
    'options' => [
        'cluster' => 'mt1', //Choose appropriate cluster (mt1 for east united states, eu for Europe)
    ],
],

Cluster information can be found next to the app name on Pusher dashboard

4) Make changes to bootstrap.js file

window.axios.defaults.headers.common = {
    // 'X-CSRF-TOKEN': window.Laravel.csrfToken, <-- Comment out if extending layouts.app file
    'X-Requested-With': 'XMLHttpRequest'
};

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'YOUR_PUSHER_KEY',
    cluster: 'mt1',
    encrypted : true
});

5) Customize your chat.blade.php with the code snippet below.

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        Chatroom
                    </div>

                    <div id="app">
                        <chat-log :messages="messages"></chat-log>
                        <chat-composer v-on:messagesent="addMessage"></chat-composer>
                    </div>

                </div>
            </div>
        </div>
    </div>
@endsection

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interactive Thumbnail Selection for HTML5 Video

Having trouble with creating thumbnails? I managed to solve the cross-domain issue using an html2canvas PHP proxy. No error messages in the Console, but the thumbnails are unfortunately not showing up - they appear transparent or white. Here is a snippet ...

[Vue alert]: Issue encountered in mounted hook: "Error: viewType "" is not accessible. Please ensure that you have loaded all essential plugins

Having some trouble using FullCalendar as a vue component in Laravel. I've followed the documentation and loaded the plugins correctly, but for some reason, they are not loading properly. https://fullcalendar.io/docs/vue Here's the Component: te ...

Leveraging the power of Vue Draggable with a dynamic computed Array

I have been utilizing the vuedraggable component available at this link: https://github.com/SortableJS/Vue.Draggable The setup I am using is as follows: <draggable v-model="filteredItems"> <div class="item" v-for="item ...

Contrasts in data manipulation within Vue.js

I have been trying to understand the reason behind this issue, but it remains a mystery to me. Let me share the code and explain the situation. I am baffled by why this problem persists and it's driving me absolutely crazy! Button: <a href=" ...

Show an item from a list in Vue.js depending on the current time

When retrieving a list of objects (trips) from an API, I need to determine if any trip object meets the following criteria: A trip object includes -> startTime, estimatedTime, begin, destination Criteria: If there is a trip where startTime + estimatedTim ...

Verify the accuracy of quiz responses with PHP and AJAX

I am working on a picture quiz that has one input field for each image. I am looking for a solution to verify if the value entered into the input field matches the correct answer. If it does match, I need to perform certain operations like adding or removi ...

Remove a particular row from a table with PHP

I have created a visually appealing table to showcase data in the following manner: ID name Delete 1 abc Delete 2 def Delete The coding snippet used for the aforementioned display is as follows: <?php $con=mysqli_connect("abc" ...

Verify that a minimum of one checkbox has been ticked according to JavaScript guidelines, with appropriate notifications in case

Need help with displaying a message when no checkbox is checked. Currently implementing JavaScript rules and messages <form method="post" enctype="multipart/form-data name="english_registration_form" id="english_registration_form" > <div cl ...

What is the best way to simulate an external class using jest?

My Vue page code looks like this: <template> // Button that triggers the submit method </template> <script> import { moveTo } from '@/lib/utils'; export default { components: { }, data() { }, methods: { async ...

Unable to retrieve the status for the specified ID through the use of AJAX

When I click the button in my app, I want to see the order status. However, currently all statuses are being displayed in the first order row. PHP: <?php $query = mysqli_query($conn, "SELECT o.orderid,o.product,o.ddate,o.pdate,k.kalibariname,o.sta ...

Building a stunning Vue application with an interactive Kendo diagram

I'm currently following the guidelines provided on https://www.telerik.com/kendo-vue-ui/components/diagram/ to implement a diagram in my standalone Vue application using .vue files. However, I encountered an issue where it fails at kendo.dataviz, sta ...

The wordpress plugin I tried using to link our contact form with InfusionSoft CRM was "Contact Form 7 - InfusionSoft Add-on," but unfortunately, it did not successfully send the contact form mail to InfusionSoft

I'm trying to save contact form submissions from Contact Form 7 to my Infusionsoft CRM using the Contact Form 7 - InfusionSoft Add-on WordPress plugin. I've added my Infusionsoft API key and App name, but unfortunately it's not functioning a ...

v-for loop to populate dropdown menu with identical values

Recently, I started working on a points counter app using Vue.js and encountered some issues with the v-for loop and dropdown menu functionality. Within my Vue.js application, I have an array of players as shown below: var app = new Vue({ el: '#l ...

Guide on how to set up routing for a Rails 5 API single page application with numerous static entry points

I'm having trouble figuring this out for some reason. My Rails 5 API app is only serving JSON. I have two VueJS front-end apps, one for the public and one for private "admin." My goal is to serve both of these static HTML files from the Rails public ...

What is the best way to remove <a> tags from an XML document?

I'm dealing with <a> tags within an XML file and I need to remove only the <a> tags. For instance: <test>This is a line with <a name="idp173968"></a> tags in it</test> I am unable to use str_replace to replace t ...

Is there a lone wanderer in the Ajax reply?

Currently working on a Wordpress project, I encountered an issue with my Ajax call. Upon making the call using jQuery, PHP returns a JSON object. However, the JavaScript response includes an unexpected "0" at the end, causing the decoding of the JSON objec ...

What is the best way to transfer information from the window method to the data function in a Vue.js application?

Is there a way to transfer information from the window method to the data function in a vuejs component? Take a look at my window method: window.authenticate = function(pid, receiptKey) { console.log("Authentication"); console.log(this) localStorag ...

problem encountered while installing npm global packages

I encountered a problem while attempting to install Vue CLI. Operating system: Windows 10, Node version: ~6.10.3 NPM version: ~3.10.10 npm WARN retry will retry, error on last attempt: Error: EBUSY: resource busy or locked, rename 'D:\Users&bso ...

Issues with Laravel 5.8 and Bootstrap not functioning properly in Jquery

Check out this link for using Bootstrap Select. The code works perfectly in the view, but when I try to implement it with jQuery below, it doesn't work. Can someone help me fix this issue? View Code: <table id="tableAppointment" style=&q ...

Cleve js does not include delimiters in its date output

In my Vue.js project, I decided to implement a date input field using cleave.js. After passing the following options: options="{date: true, delimiter: '/', datePattern: ['m', 'd', 'Y']}" I encountered an issue wh ...