|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Http\Controllers\Api; |
| 4 | + |
| 5 | +use App\Http\Controllers\Controller; |
| 6 | +use App\Http\Requests\StoreCategoryRequest; |
| 7 | +use App\Http\Requests\UpdateCategoryRequest; |
| 8 | +use App\Http\Resources\CategoryResource; |
| 9 | +use App\Models\Category; |
| 10 | + |
| 11 | +class CategoryController extends Controller |
| 12 | +{ |
| 13 | + /** |
| 14 | + * Display a listing of the resource. |
| 15 | + */ |
| 16 | + public function index() |
| 17 | + { |
| 18 | + $sortField = request('sort_field', 'updated_at'); |
| 19 | + $sortDirection = request('sort_direction', 'desc'); |
| 20 | + |
| 21 | + $categories = Category::query() |
| 22 | + ->orderBy($sortField, $sortDirection) |
| 23 | + ->latest() |
| 24 | + ->get(); |
| 25 | + |
| 26 | + return CategoryResource::collection($categories); |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * Store a newly created resource in storage. |
| 31 | + */ |
| 32 | + public function store(StoreCategoryRequest $request) |
| 33 | + { |
| 34 | + $data = $request->validated(); |
| 35 | + $data['created_by'] = $request->user()->id; |
| 36 | + $data['updated_by'] = $request->user()->id; |
| 37 | + $category = Category::create($data); |
| 38 | + |
| 39 | + return new CategoryResource($category); |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Update the specified resource in storage. |
| 44 | + */ |
| 45 | + public function update(UpdateCategoryRequest $request, Category $category) |
| 46 | + { |
| 47 | + $data = $request->validated(); |
| 48 | + $data['updated_by'] = $request->user()->id; |
| 49 | + $category->update($data); |
| 50 | + |
| 51 | + return new CategoryResource($category); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Remove the specified resource from storage. |
| 56 | + */ |
| 57 | + public function destroy(Category $category) |
| 58 | + { |
| 59 | + $category->delete(); |
| 60 | + |
| 61 | + return response()->noContent(); |
| 62 | + } |
| 63 | +} |
0 commit comments