forked from eatvio/eatvio-infra
81 lines
2.6 KiB
PHP
Executable File
81 lines
2.6 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Chat;
|
|
use App\Models\User;
|
|
use Illuminate\Contracts\View\Factory as ViewFactory;
|
|
use Illuminate\Contracts\View\View;
|
|
|
|
class ChatController extends Controller
|
|
{
|
|
public function index(): View|ViewFactory
|
|
{
|
|
// $_ = "from_user_id to_user_id";
|
|
$curUserId = Auth()->user()->id;
|
|
$lastChatUsers = Chat::select(['from_user_id', 'to_user_id'])
|
|
->where('from_user_id', $curUserId)
|
|
->orWhere('to_user_id', $curUserId)
|
|
->get()
|
|
->map(fn ($e) => [$e['from_user_id'], $e['to_user_id']])
|
|
->flatten()
|
|
->unique()
|
|
->filter(fn ($e) => $e !== $curUserId)
|
|
->values()
|
|
->map(fn ($id) => User::find($id));
|
|
|
|
$lastChatMessage = Chat::withLastUserMessage($curUserId);
|
|
|
|
$lastChatRecipientUserId = $lastChatMessage->count() ? $lastChatMessage['from_user_id'] : null;
|
|
|
|
if (! is_null($lastChatRecipientUserId) && $lastChatMessage['from_user_id'] === $curUserId) {
|
|
$lastChatRecipientUserId = $lastChatMessage['to_user_id'];
|
|
}
|
|
|
|
return view(
|
|
'chat.index',
|
|
[
|
|
'lastChatRecipientUserId' => $lastChatRecipientUserId,
|
|
'lastChatUsers' => $lastChatUsers,
|
|
'curUserId' => $curUserId,
|
|
'chanId' => $this->makeChanName($curUserId, $lastChatRecipientUserId),
|
|
]
|
|
);
|
|
}
|
|
|
|
public function show(int $lastChatUser): View|ViewFactory
|
|
{
|
|
$lastChatUser = User::find($lastChatUser);
|
|
// $_ = "from_user_id to_user_id";
|
|
$curUserId = Auth()->user()->id;
|
|
|
|
$lastChatUsers = Chat::select(['from_user_id', 'to_user_id'])
|
|
->where('from_user_id', $curUserId)
|
|
->orWhere('to_user_id', $curUserId)
|
|
->get()
|
|
->map(fn ($e) => [$e['from_user_id'], $e['to_user_id']])
|
|
->flatten()
|
|
->unique()
|
|
->filter(fn ($e) => $e !== $curUserId)
|
|
->values()
|
|
->map(fn ($id) => User::find($id));
|
|
|
|
return view(
|
|
'chat.index',
|
|
[
|
|
'lastChatRecipientUserId' => $lastChatUser->id,
|
|
'lastChatUsers' => $lastChatUsers,
|
|
'curUserId' => $curUserId,
|
|
'chanId' => $this->makeChanName($curUserId, $lastChatUser->id),
|
|
]
|
|
);
|
|
}
|
|
|
|
private function makeChanName(?int $from = null, ?int $to = null): string
|
|
{
|
|
return (int) $from < (int) $to
|
|
? $from.'_'.$to
|
|
: $to.'_'.$from;
|
|
}
|
|
}
|