66use App \Http \Requests \StoreCategoryRequest ;
77use App \Http \Resources \CategoryResource ;
88use App \Models \Category ;
9+ use Exception ;
910use Illuminate \Http \Request ;
1011use Illuminate \Http \Resources \Json \ResourceResponse ;
1112
1213class CategoryController extends Controller
1314{
14- public function index (){
15- // return Category::orderBy('id')->get(); // Laravel will return as JSON format.
16- // We only want id, name filed in the response.
17- // $categories = Category::select('id','name')->get(); This is efficient approach.
18- // But we are already defined our toArray response
15+ public function index ()
16+ {
17+ // return Category::orderBy('id')->get(); // Laravel will return as JSON format.
18+ // We only want id, name filed in the response.
19+ // $categories = Category::select('id','name')->get(); This is efficient approach.
20+ // But we are already defined our toArray response
1921 $ categories = Category::all ();
2022 return CategoryResource::collection ($ categories ); // Now we are returning resource collection
2123 }
2224
2325 // Route model binding
24- public function show (Category $ category ){
26+ public function show (Category $ category )
27+ {
2528 // return $category; // It will return category as a JSON response object and it is the magic of Laravel
2629
2730 // It is difficult to return only id and name with the Route model binding
@@ -33,9 +36,15 @@ public function show(Category $category){
3336 }
3437
3538 // Post store
36- public function store (StoreCategoryRequest $ request ) {
39+ public function store (StoreCategoryRequest $ request )
40+ {
41+ try {
3742 $ category = Category::create ($ request ->all ());
38- return new CategoryResource ($ category );
43+ // 201 means Created Successfully
44+ return (new CategoryResource ($ category ))->response ()->setStatusCode (201 );
45+ } catch (Exception $ exception ) { // Anything that went wrong
46+ abort (500 , 'Could not create category ' );
47+ }
3948 }
4049
4150
0 commit comments