0

我尝试在我的网站上添加一个聊天扩展,观看了很多视频课程,Laravel 和 Pusher 使用用户。网站正常运行

broadcasting(new MyEvent('my-event'));

但是如果我在 return line- 之前添加 line- ,则会给出 500 Internal Server Error 。发送的消息正在保存到数据库但没有返回值...请帮助我

我的 ChatEvent.php

use App\Chat;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Broadcasting\PresenceChannel;
....
class ChatEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $chat;

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

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

我的 ChatController.php

use Illuminate\Http\Request;
use App\Chat;
use App\Events\ChatEvent;

class ChatController extends Controller
{
public function __construct(){
    $this->middleware('auth');
}

public function index(){
    return view('chat.chat');
}

public function fetchAllMessages(){
    return Chat::with('user')->get();
}

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

    broadcast(new ChatEvent($chat->load('user')))->toOthers();

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

VueJs 发布和获取代码

<script>
    export default {

        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>

路线和渠道

Route::get('/chats','ChatController@index');
Route::get('/messages','ChatController@fetchAllMessages');
Route::post('/messages','ChatController@sendMessage');

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

Pusher's AppKey,Secret,ID and Cluster OK, Broadcaster-Driver: pusher Everywhere

4

0 回答 0