Skip to content
Advertisement

Websocket chat in Laravel isnt real time

I am creating a chat in Laravel Websocket i followed a youtube tutorial and the message goes to the other user they can talk with each other but i need to reload the page to get the message that was sent,its not real time.At the console before i send a message it says this error: Failed to load resource: the server responded with a status of 404 (Not Found) and than after sending says this POST http://127.0.0.1:8000/broadcasting/auth 404 (Not Found) .I have run “php artisan websocket:serve” command in terminal.Thanks in advance

ChatsController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppMessage;
use AppEventsMessageSent;

class ChatsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');//only authenticated users can acces to chat
    }

    public function index()
    {
        return view('chats');
    }

    public function fetchMessages()
    {
        return Message::with('user')->get();
    }

    public function sendMessage(Request $request)
    {
        $message = auth()->user()->messages()->create([
            'message' => $request->message
        ]);

        broadcast(new MessageSent($message->load('user')))->toOthers();

        return ['status' => 'success'];
    }
}

User.php

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

Message.php

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

web.php

<?php
use AppUser;
use AppDepartment;

use AppEventsWebsocketDemoEvent;
/*
|--------------------------------------------------------------------------
| 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 () {
    broadcast(new WebsocketDemoEvent('some data'));
    return view('welcome');
});
Route::get('/page', function () {
    return view('admin.page');
});
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
Route::group(['middleware' => ['auth','admin']], function  () {
    Route::get('/role-register','AdminDashboardController@registered');
    Route::delete('/role-delete/{id}', 'AdminDashboardController@registerdelete');//delete user
    Route::post('/save-user', 'AdminDashboardController@store');

    Route::get('/department', 'AdminDepartmentController@index');
    Route::post('/save-department', 'AdminDepartmentController@store');
    Route::get('/department-edit/{id}', 'AdminDepartmentController@edit');//edit department
    Route::put('/department-update/{id}', 'AdminDepartmentController@update');
    Route::delete('/department-delete/{id}', 'AdminDepartmentController@delete');//delete department  


});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');

Route::get('/chats', 'ChatsController@index');//chats
Route::get('/messages', 'ChatsController@fetchMessages');//messages
Route::post('/messages', 'ChatsController@sendMessage');//messages

Route::get('/dashboard', 'AdminDashboardController@dbcheck');//DATABASE
Route::get('/user-edit/{id}', 'HomeController@registeredit');
Route::get('/role-edit/{id}', 'AdminDashboardController@registeredit');//edit user
Route::put('/role-register-update/{id}', 'AdminDashboardController@registerupdate');

Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');


Route::get('store_image', 'StoreImageController@index');
Route::post('store_image/insert_image', 'StoreImageController@insert_image');
Route::get('store_image/fetch_image/{id}', 'StoreImageController@fetch_image');
Route::get('/page',array('as'=>'jquery.treeview','uses'=>'AdminDepartmentController@treeView'));
Route::get('/pageusers', 'AdminDepartmentController@usersdep');




ChatsComponent.vue

<template>
  <div class="row">

    <div class="col-8">
      <div class="card card-default">
        <div class="card-header">Messages</div>
        <div class="card-body p-0">
          <ul class="list-unstyled" style="height:300px; overflow-y:scroll">
            <li class="p-2" v-for="(message, index) in messages" :key="index">
              <strong>{{ message.user.name }}</strong>
              {{  message.message }}
            </li>
          </ul>
        </div>
        <input
        @keyup.enter="sendMessage"
        v-model="newMessage"
        type="text"
        name="message"
        placeholder="Enter your message"
        class="form-control">

      </div>
      <span class="text-muted">user is typing...</span>
    </div>

    <div class="col-4">
      <div class="card card-default">
        <div class="card-header">Active Users</div>
        <div class="card-body">
          <ul>
            <li class="py-2">{{ user.name }}</li>
          </ul>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
export default {

  props:['user'],

  data() {
    return {
      messages: [],
      newMessage:''
    }

  },

  created() {
    this.fetchMessages();

    Echo.join('chat')
        .listen('MessageSent',(event) => {
        this.messages.push(event.message);
        })
  },

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

    },

    sendMessage(){
      this.messages.push({
        user: this.user,
        message: this.newMessage

      });
      axios.post('messages', {message: this.newMessage});

      this.newMessage = '';
    }

  }

}
</script>

MessageSent.php

<?php

namespace AppEvents;

use IlluminateBroadcastingChannel;
use IlluminateQueueSerializesModels;
use IlluminateBroadcastingPrivateChannel;
use IlluminateBroadcastingPresenceChannel;
use IlluminateFoundationEventsDispatchable;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateContractsBroadcastingShouldBroadcast;
use AppMessage;

class MessageSent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

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

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

Advertisement

Answer

Sorry to post this as an answer, but you need 50 reputation to place a comment. Did you uncomment the AppProvidersBroadcastServiceProvider::class, line in your config/app.php?

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement