Real-time user messages with Laravel

I really need help as well as examples for this problem. I need a conversation system on my site, for example Facebook (send a message to the conversation and upload messages without refreshing the page). I think there are many ways to solve this problem: broadcast, long polling, or simple AJAX. It would be very helpful if I had an example of using broadcasts. Below I tried to implement this.

Table 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 ID');
        $table->foreign('user_two')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();
    });

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

Conversation model

    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 post

    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

Thanks for helping me with this.

+4
source share
1 answer

, , Laravel Echo. redis, socket.io laravel echo server. .

0

Source: https://habr.com/ru/post/1679344/


All Articles