validate([ 'groupBy' => ['nullable', 'string', 'in:region'], ]); $branches = Branch::query() ->where('active', true) ->get() ->map(fn ($branch) => [ 'id' => $branch->id, 'name' => $branch->name, 'region' => $branch->region, ]); if ($request->filled('groupBy')) { $branches = $branches->groupBy('region'); } return response()->json($branches); } }