FollowerController.php 1.94 KB
<?php

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

use App\Helpers\JsonResource;
use App\Models\User;
use App\Models\UserFollowRelation;
use App\Support\Controller;
use Auth;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class FollowerController 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);

        $followerQuery = UserFollowRelation::query()->selectRaw('follower_id,is_read,created_at as follower_at')->where('following_id', $id)->groupBy('follower_id');

        $data = User::with(['userTag:id,name,icon,frame', 'authTags:id,name'])
            ->when($request->get('text'), fn(Builder $query, string $name) => $query->where('nick_name', 'like', '%' . $name . '%'))
            ->select(['id', 'nick_name', 'avatar', 'identity', 'user_tag_id', 'follower_at', 'is_read'])
            ->addSelect([
                'is_follow'    => UserFollowRelation::query()->selectRaw('IFNULL(COUNT(*),0)')->whereColumn('following_id', 'users.id')->where('follower_id', Auth::id()),
                'is_following' => UserFollowRelation::query()->selectRaw('IFNULL(COUNT(*),0)')->whereColumn('follower_id', 'users.id')->where('following_id', Auth::id())
            ])
            ->joinSub($followerQuery, 'follower', 'follower.follower_id', 'users.id')
            ->latest('follower_at')
            ->paginate($size);

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

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