简体   繁体   English

使用Laravel的实时用户消息

[英]Real-time user messages with Laravel

I really need some help, as well as examples for this issue. 我真的需要一些帮助,以及这个问题的例子。 I need a conversation system on my site like Facebook (send message to conversation and load messages without page refreshing). 我需要在我的网站上建立一个会话系统,如Facebook(向对话发送消息并加载消息而不刷新页面)。 I think there are many ways that this problem can be solved: broadcasting, long-polling or simple AJAX. 我认为有很多方法可以解决这个问题:广播,长轮询或简单的AJAX。 It would be greatly appreciated if I could have an example using broadcasts. 如果我能有一个使用广播的例子,我将不胜感激。 Below is what I have come up with to try to implement this. 以下是我试图实现这一点的方法。

Table conversations 表格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();
    });

Table messages 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();
        });

Controller 调节器

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,
    ]);
}

Model Conversation 模型对话

    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');
    }
}

Model Message 模型消息

    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');
    }
}

View 视图

@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

Thank-you for assisting me with this. 谢谢你帮我这个。

What you are looking for is Laravel Echo . 您正在寻找的是Laravel Echo This will work well with redis server, socket.io and laravel echo server . 这适用于redis服务器,socket.io和laravel echo服务器 It's really nice and easy to setup. 这真的很好,很容易设置。 Check out example application here 在这里查看示例应用程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM