VisitorController.php 1.53 KB
<?php

namespace App\Http\Container\AppSection\Controllers\User;

use App\Helpers\JsonResource;
use App\Models\User;
use App\Models\UserVisitorRelation;
use App\Support\Controller;
use Auth;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

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

    /**
     * @param \Illuminate\Http\Request $request
     * @param int                      $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function __invoke(Request $request, int $id): JsonResponse
    {
        $size = $request->get('size', 10);

        $visitorQuery = UserVisitorRelation::query()->where('user_id', $id)
            ->selectRaw('visitor_id,is_read,max(created_at) as last_visitor_at')
            ->where('created_at', '>=', Carbon::now()->subDays(30))
            ->groupBy('visitor_id');

        $data = User::with(['userTag:id,name,icon,frame', 'authTags:id,name'])
            ->select(['id', 'nick_name', 'avatar', 'identity', 'user_tag_id', 'last_visitor_at', 'is_read'])
            ->joinSub($visitorQuery, 'visitor', 'visitor.visitor_id', 'users.id')
            ->latest('last_visitor_at')
            ->paginate($size);

        if ($id === Auth::id()) {
            UserVisitorRelation::query()->where('user_id', $id)->where('is_read', 0)->update(['is_read' => 1]);
        }

        return JsonResource::success(JsonResource::SUCCESS, ['data' => $data->items(), 'count' => $data->total()]);
    }
}