skip to Main Content

I have followed all the steps and it is displaying the chat page without error but still not working, Click this Link for the Detailed Code if required..

I have done all the steps properly and there is no error return but still code is not working. Any help will be appreciated. Project has multi auth system.

VIEW

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <h2>Messages</h2>

            <div
                class="clearfix"
                v-for="message in messages"
            >
                @{{ message.user.name }}: @{{ message.message }}
            </div>

            <div class="input-group">
                <input
                    type="text"
                    name="message"
                    class="form-control"
                    placeholder="Type your message here..."
                    v-model="newMessage"
                    @keyup.enter="sendMessage"
                >

                <button
                    class="btn btn-primary"
                    @click="sendMessage"
                >
                    Send
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

Message Controller

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class MessageController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    
    public function index()
    {
        return Message::with('user')->get();
    }

    public function store(Request $request)
    {
        $user = Auth::user();

        $message = $user->messages()->create([
        'message' => $request->input('message')
        ]);
    // send event to listeners
        broadcast(new MessageSentEvent($message, $user))->toOthers();

    return [
        'message' => $message,
        'user' => $user,
        ];
    }

}

Message Model

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Message extends Model
{
    //use HasFactory;
    protected $fillable = [
        'message'
    ];

    public function user() {
        return $this->belongsTo(User::class);
    }
}

app.js

    require('./bootstrap');
const app = new Vue({
    el: '#app',

    data: {
        messages: [],
        newMessage: ''
    },

    created() {
        this.fetchMessages();

        Echo.private('chat')
            .listen('MessageSentEvent', (e) => {
                this.messages.push({
                    message: e.message.message,
                    user: e.user
                });
            });
    },

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

        addMessage(message) {
            axios.post('/messages', {
                message
            }).then(response => {
                this.messages.push({
                    message: response.data.message.message,
                    user: response.data.user
                });
            });
        },

        sendMessage() {
            this.addMessage(this.newMessage);
            this.newMessage = '';
        }
    }
});

bootstrap.js

window._ = require('lodash');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

try {
    window.Popper = require('popper.js').default;
    window.$ = window.jQuery = require('jquery');

    require('bootstrap');
} catch (e) {}

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// 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,
//     forceTLS: true
// });
import Echo from 'laravel-echo';
import Larasocket from 'larasocket-js';
window.Echo = new Echo({
    broadcaster: Larasocket,
    token: process.env.MIX_LARASOCKET_TOKEN,
});

User controller

   <?php

namespace AppModels;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    public function messages() {
        return $this->hasMany(Message::class);
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'role',
        'phone_number', 
        'isVerified'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'role',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Route: Web.php

<?php

use IlluminateSupportFacadesRoute;
use AppHttpControllers HomeController;
use AppHttpControllersauthLoginController;

use AppHttpControllers AdminController;
use AppHttpControllers TutorController;
use AppHttpControllers StudentController;
use AppHttpControllers GuestController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/course_categories', function () {
    return view('course_categories');
});

Route::get('/tutor_req', function () {
    return view('tutor_req');
});

Route::get('/course', function () {
    return view('course');
});

Route::get('/chat', function () {
    return view('chat');
});

Auth::routes();

Route::get('/home', [HomeController::class, 'index'])->name('home');

//GET DASHBOARDS
Route::get('/admin', [AdminController::class, 'index'])->name('admin')->middleware('admin');
Route::get('/tutor', [TutorController::class, 'index'])->name('tutor')->middleware('tutor');
Route::get('/student', [StudentController::class, 'index'])->name('student')->middleware('student');

//POST AD
Route::get('/tutor_require', [TutorController::class, 'putReq'])->name('post.tutor.ad')->middleware('tutor');
Route::post('/tutor_create', [TutorController::class, 'create_req'])->name('create.tutor.ad')->middleware('tutor');
Route::get('/student_require', [StudentController::class, 'putReq'])->name('post.student.ad')->middleware('student');
Route::post('/student_create', [StudentController::class, 'create_req'])->name('create.student.ad')->middleware('student');


//PROFILE
Route::get('/tutor_profile', [TutorController::class, 'profile'])->name('get.tutor.profile')->middleware('tutor');
Route::get('/student_profile', [StudentController::class, 'profile'])->name('get.student.profile')->middleware('student');

//DETAIL VIEW
Route::get('/tutor_view/{id}', [TutorController::class, 'detail_view'])->name('get.tutor.detail')->middleware('tutor');
Route::get('/student_view/{id}', [StudentController::class, 'detail_view'])->name('get.student.detail')->middleware('student');

// Google login
Route::get('login/google', [LoginController::class, 'redirectToGoogle'])->name('login.google');
Route::get('login/google/callback', [LoginController::class, 'handleGoogleCallback']);

// Facebook login
Route::get('login/facebook', [LoginController::class, 'redirectToFacebook'])->name('login.facebook');
Route::get('login/facebook/callback', [LoginController::class, 'handleFacebookCallback']);

// Request Tutor
Route::post('/req_confirm', [GuestController::class, 'create_req'])->name('get.req.confirm');
Route::get('/guide', [GuestController::class, 'guide'])->name('guide');

Route::view('/chat', 'chat')->middleware('auth');
Route::resource('messages', 'MessageController')->only([
    'index',
    'store'
]);

Route: Channels.php

<?php

use IlluminateSupportFacadesBroadcast;

/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/

Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Broadcast::channel('chat', function () {
    return IlluminateSupportFacadesAuth::check();
});

enter image description here

2

Answers


  1. You didn’t post your MessageEvent and the JS part.

    Ideally, you want to ensure that in your event, your MessageEvent implements ShouldBroadcast and also ensure that it uses InteractWithSockets (this is because you are using ->toOthers() and according to laravel documentation you need to ensure it uses it). You also want to listen for the events on your frontend. check this section of the document

    ...///
    use IlluminateBroadcastingInteractsWithSockets;
    use IlluminateContractsBroadcastingShouldBroadcast;
    use IlluminateFoundationEventsDispatchable;
    ...///
    
    class NewTradeChatEvent implements ShouldBroadcast
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;
    
    Login or Signup to reply.
  2. Check your config.app and verify the BroadAppProvidersBroadcastServiceProvider::class is uncommented.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search