Laravel 的实时用户消息

Posted

技术标签:

【中文标题】Laravel 的实时用户消息【英文标题】:Real-time user messages with Laravel 【发布时间】:2017-11-17 22:16:45 【问题描述】:

我真的需要一些帮助,以及这个问题的示例。我需要一个像 Facebook 这样的网站上的对话系统(向对话发送消息并加载消息而不刷新页面)。我认为有很多方法可以解决这个问题:广播、长轮询或简单的 AJAX。如果我有一个使用广播的例子,将不胜感激。以下是我想出的尝试实现这一点的方法。

conversations

Schema::create('conversations', function (Blueprint $table) 
        $table->increments('id');
        $table->integer('user_one')->unsigned()->index()->comment('Sender ID');
        $table->foreign('user_one')->references('id')->on('users')->onDelete('cascade');
        $table->integer('user_two')->unsigned()->index()->comment('Inrerlocutor's ID');
        $table->foreign('user_two')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();
    );

messages

 Schema::create('messages', function (Blueprint $table) 
            $table->increments('id');
            $table->text('message')->comment('Message text');
            $table->boolean('is_seen')->default(0);
            $table->boolean('deleted_from_sender')->default(0);
            $table->boolean('deleted_from_receiver')->default(0);
            $table->integer('user_id')->unsigned()->index()->comment('Sender ID');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->integer('conversation_id')->unsigned()->index()->comment('Conversation ID');
            $table->foreign('conversation_id')->references('id')->on('conversations')->onDelete('cascade');
            $table->timestamps();
        );

控制器

public function sendMessage($id, SendMessageRequest $request)

    if ($id == Auth::id())
    
        return redirect('/');
    

    $conversation = Conversation::whereIn('user_one', [Auth::id(), $id])
        ->whereIn('user_two', [$id, Auth::id()])
        ->first(); // Get conversation data

    /**
     * Create a new conv. when doesnt exists
     */
    if ($conversation == NULL)
    
        $newConversation = Conversation::create([
            'user_one' => Auth::id(),
            'user_two' => $id,
        ]);
    

    /**
     * Create message
     */
    Message::create([
        'message' => $request->get('message'),
        'user_id' => Auth::id(),
        'conversation_id' => $conversation !== NULL ? $conversation->id : $newConversation->id,
    ]);

    return redirect(route('mails.chat', $id));


/**
 * Chat History
 */
public function chat($id)

    $user = User::find($id); // Get user data
    $title = 'Диалог с ' . $user->name . ' ' . $user->lastname; // Page title

    if ($id == Auth::id())
    
        return redirect('/');
    

    $conversation = Conversation::whereIn('user_one', [Auth::id(), $id])
        ->whereIn('user_two', [$id, Auth::id()])
        ->first(); // Get conv. data

    $messages = '';
    if ($conversation !== NULL)
    
        $messages = Message::where('conversation_id', $conversation->id)->paginate(30); // Get messages
    

    return view('mails.chat', [
        'title' => $title,
        'conversation' => $conversation,
        'messages' => $messages,
        'user' => $user,
    ]);

模型对话

    class Conversation extends Model

    protected $table = 'conversations';
    protected $fillable = ['user_one', 'user_two'];
    protected $dates = ['created_at', 'updated_at'];

    public function user() 
        return $this->belongsToMany('App\User');
    

模型消息

    class Message extends Model

    protected $table = 'messages';
    protected $fillable = ['message', 'is_seen', 'deleted_from_sender', 'deleted_from_receiver', 'user_id', 'conversation_id'];
    protected $dates = ['created_at', 'updated_at'];

    public function user() 
        return $this->belongsToMany('App\User');
    

    public function conversation() 
        return $this->belongsToMany('App\Conversation');
    

查看

@extends('layouts.app')

@section('content')

-- Simple display messages --
@if ($conversation !== NULL && count($messages) !== 0)
    @foreach($messages as $message)
        @php($sender = App\User::find($message->user_id))

        <div>
            <b> $sender->name   $sender->lastname </b><br>
             $message->message 
        </div>
    @endforeach
@else
    <div class="alert alert-info">No messages.</div>
@endif

<form id="submit" method="post" action=" route('mails.sendMessage', $user->id) ">
     csrf_field() 
    <b>Message:</b><br>
    <textarea name="message"></textarea>

    <button type="submit">Send!</button>
</form>

@endsection

感谢您在这方面帮助我。

【问题讨论】:

如果您要忽略 MS Edge,还有 html5 服务器发送事件 谷歌“laravel 聊天应用” @Fr0zenFyr 这对我没有帮助。只是让情况变得更糟 :c 没有实施私人聊天的例子。 你试过了吗:github.com/dazzz1er/confer @nathan6137 感谢您的回答。我想使用一个可以在站点内运行的应用程序,而不使用第三方服务(如 Pusher)。不幸的是,它仅支持 100 个用户,采用免费资费计划...... 【参考方案1】:

您正在寻找的是Laravel Echo。这将适用于 redis 服务器、socket.io 和laravel echo server。它非常好且易于设置。查看示例应用程序here

【讨论】:

以上是关于Laravel 的实时用户消息的主要内容,如果未能解决你的问题,请参考以下文章

laravel 5.8 实现消息推送

用户连接时显示消息 laravel 6 *

Laravel接收来自Pusher的消息

Laravel 4.2 应用程序在上传实时服务器后发生不必要的重定向

Laravel - 更改身份验证用户的错误消息

在 Laravel 中获取每个用户的最新消息(行)