Я создаю чат в Laravel Websocket. Я следовал учебному пособию по YouTube, и сообщение отправляется другому пользователю, с которым они могут общаться друг с другом, но мне нужно перезагрузить страницу, чтобы получить сообщение, которое было отправлено, это не реально. время. На консоли перед отправкой сообщения выдается следующее сообщение об ошибке: Не удалось загрузить ресурс: сервер ответил с состоянием 404 (не найдено) , а после отправки это говорит POST http://127.0.0.1: 8000 / широковещание / аутентификация 404 (не найдено) . Я запустил команду "php artisan websocket: serve" в терминале. Заранее спасибо
ChatsController. php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Message;
use App\Events\MessageSent;
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'];
}
}
Пользователь. php
public function messages()
{
return $this->hasMany(Message::class);
}
Сообщение. php
public function user()
{
return $this->belongsTo(User::class);
}
Интернет. php
<?php
use App\User;
use App\Department;
use App\Events\WebsocketDemoEvent;
/*
|--------------------------------------------------------------------------
| 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','Admin\DashboardController@registered');
Route::delete('/role-delete/{id}', 'Admin\DashboardController@registerdelete');//delete user
Route::post('/save-user', 'Admin\DashboardController@store');
Route::get('/department', 'Admin\DepartmentController@index');
Route::post('/save-department', 'Admin\DepartmentController@store');
Route::get('/department-edit/{id}', 'Admin\DepartmentController@edit');//edit department
Route::put('/department-update/{id}', 'Admin\DepartmentController@update');
Route::delete('/department-delete/{id}', 'Admin\DepartmentController@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', 'Admin\DashboardController@dbcheck');//DATABASE
Route::get('/user-edit/{id}', 'HomeController@registeredit');
Route::get('/role-edit/{id}', 'Admin\DashboardController@registeredit');//edit user
Route::put('/role-register-update/{id}', 'Admin\DashboardController@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'=>'Admin\DepartmentController@treeView'));
Route::get('/pageusers', 'Admin\DepartmentController@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 App\Events;
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;
use App\Message;
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 \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PresenceChannel('chat');
}
}