6
6
use App \Http \Requests \StoreCategoryRequest ;
7
7
use App \Http \Resources \CategoryResource ;
8
8
use App \Models \Category ;
9
+ use Exception ;
9
10
use Illuminate \Http \Request ;
10
11
use Illuminate \Http \Resources \Json \ResourceResponse ;
11
12
12
13
class CategoryController extends Controller
13
14
{
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
19
21
$ categories = Category::all ();
20
22
return CategoryResource::collection ($ categories ); // Now we are returning resource collection
21
23
}
22
24
23
25
// Route model binding
24
- public function show (Category $ category ){
26
+ public function show (Category $ category )
27
+ {
25
28
// return $category; // It will return category as a JSON response object and it is the magic of Laravel
26
29
27
30
// It is difficult to return only id and name with the Route model binding
@@ -33,9 +36,15 @@ public function show(Category $category){
33
36
}
34
37
35
38
// Post store
36
- public function store (StoreCategoryRequest $ request ) {
39
+ public function store (StoreCategoryRequest $ request )
40
+ {
41
+ try {
37
42
$ 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
+ }
39
48
}
40
49
41
50
0 commit comments