withCount('channels'); $username = trim((string) $request->query('username', '')); $status = $request->query('status'); if ($username !== '') { $q->where('username', 'like', '%'.$username.'%'); } if ($status !== null && $status !== '') { $q->where('status', (int) $status); } $sortable = ['id', 'username', 'status', 'created_at', 'updated_at']; $field = (string) $request->query('field', 'id'); $order = strtolower((string) $request->query('order', 'desc')) === 'asc' ? 'asc' : 'desc'; if (! in_array($field, $sortable, true)) { $field = 'id'; } $q->orderBy($field, $order); $limit = max(1, min(100, (int) $request->query('limit', 15))); $page = max(1, (int) $request->query('page', 1)); $paginator = $q->paginate($limit, ['*'], 'page', $page); $data = collect($paginator->items())->map(function (User $u) { return [ 'id' => $u->id, 'username' => $u->username, 'status' => (int) $u->status, 'comment' => $u->comment ?: '', 'channels_count' => (int) $u->channels_count, 'created_at' => optional($u->created_at)->format('Y-m-d H:i:s'), 'updated_at' => optional($u->updated_at)->format('Y-m-d H:i:s'), ]; })->values(); return response()->json([ 'code' => 0, 'msg' => '', 'count' => $paginator->total(), 'data' => $data, ]); } public function store(Request $request) { $data = $request->validate([ 'username' => ['required', 'string', 'max:64', 'alpha_dash', Rule::unique('users', 'username')], 'password' => ['required', 'string', 'min:6', 'max:128'], 'comment' => ['nullable', 'string', 'max:255'], 'status' => ['nullable', 'integer', Rule::in([0, 1])], ]); $user = User::query()->create([ 'username' => $data['username'], 'password' => $data['password'], 'comment' => $data['comment'] ?? null, 'status' => (int) ($data['status'] ?? 1), ]); return response()->json(['code' => 0, 'msg' => 'ok', 'data' => ['id' => $user->id]]); } public function update(Request $request, User $agent) { $data = $request->validate([ 'password' => ['nullable', 'string', 'min:6', 'max:128'], 'comment' => ['nullable', 'string', 'max:255'], 'status' => ['nullable', 'integer', Rule::in([0, 1])], ]); if (array_key_exists('comment', $data)) { $agent->comment = $data['comment']; } if (array_key_exists('status', $data) && $data['status'] !== null) { $agent->status = (int) $data['status']; } if (! empty($data['password'])) { $agent->password = $data['password']; } $agent->save(); return response()->json(['code' => 0, 'msg' => 'ok']); } public function channels(User $agent) { $rows = Channel::query() ->where('user_id', $agent->id) ->orderByDesc('id') ->get() ->map(fn (Channel $c) => [ 'id' => $c->id, 'channel_id' => $c->channel_id, 'status' => (int) $c->status, 'remark' => $c->remark ?: '', 'links' => $c->supportLinks(), ]) ->values(); return response()->json(['code' => 0, 'msg' => '', 'data' => $rows]); } }