Load up the item counts with the individual API methods for accurate numbers without n+1

Signed-off-by: snipe <snipe@snipe.net>
This commit is contained in:
snipe 2023-01-10 16:17:03 -08:00
parent b66cd313b9
commit 825df2cf75

View file

@ -10,6 +10,7 @@ use App\Models\Category;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Http\Requests\ImageUploadRequest; use App\Http\Requests\ImageUploadRequest;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
class CategoriesController extends Controller class CategoriesController extends Controller
{ {
@ -107,7 +108,7 @@ class CategoriesController extends Controller
public function show($id) public function show($id)
{ {
$this->authorize('view', Category::class); $this->authorize('view', Category::class);
$category = Category::findOrFail($id); $category = Category::withCount('assets as assets_count', 'accessories as accessories_count', 'consumables as consumables_count', 'components as components_count', 'licenses as licenses_count')->findOrFail($id);
return (new CategoriesTransformer)->transformCategory($category); return (new CategoriesTransformer)->transformCategory($category);
} }
@ -126,10 +127,18 @@ class CategoriesController extends Controller
{ {
$this->authorize('update', Category::class); $this->authorize('update', Category::class);
$category = Category::findOrFail($id); $category = Category::findOrFail($id);
if ($category->category_type !== $request->input('category_type')) {
return response()->json(
Helper::formatStandardApiResponse('error', null, trans('admin/categories/message.update.cannot_change_category_type'))
);
}
$category->fill($request->all()); $category->fill($request->all());
$category->category_type = strtolower($request->input('category_type'));
$category = $request->handleImages($category); $category = $request->handleImages($category);
if ($category->save()) { if ($category->save()) {
return response()->json(Helper::formatStandardApiResponse('success', $category, trans('admin/categories/message.update.success'))); return response()->json(Helper::formatStandardApiResponse('success', $category, trans('admin/categories/message.update.success')));
} }
@ -148,7 +157,7 @@ class CategoriesController extends Controller
public function destroy($id) public function destroy($id)
{ {
$this->authorize('delete', Category::class); $this->authorize('delete', Category::class);
$category = Category::findOrFail($id); $category = Category::withCount('assets as assets_count', 'accessories as accessories_count', 'consumables as consumables_count', 'components as components_count', 'licenses as licenses_count')->findOrFail($id);
if (! $category->isDeletable()) { if (! $category->isDeletable()) {
return response()->json( return response()->json(