Skip to content

Commit 2cb68f8

Browse files
author
ahmadhuss
committed
feat: Getting Single Category Record & API Resource
1 parent 35e3242 commit 2cb68f8

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

app/Http/Controllers/Api/CategoryController.php

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,21 @@
1010
class CategoryController extends Controller
1111
{
1212
public function index(){
13-
return Category::orderBy('id')->get(); // Laravel will return as JSON format.
13+
// return Category::orderBy('id')->get(); // Laravel will return as JSON format.
14+
// We only want id, name filed in the response.
15+
return Category::select('id','name')->get();
1416
}
17+
18+
// Route model binding
19+
public function show(Category $category){
20+
return $category; // It will return category as a JSON response object and it is the magic of Laravel
21+
22+
// It is difficult to return only id and name with the Route model binding
23+
// There are only 2 ways:
24+
// 1.Either you can use collection methods to filter
25+
// 2.But now it is time to introduce API resources which will contain set of rules for the API.
26+
// php artisan make:resource CategoryResource
27+
}
28+
29+
1530
}

routes/api.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,10 @@
1919
return $request->user();
2020
});
2121

22-
// API route
22+
// API route all methods are same like ResourceController
23+
// index, |create, store($request)|, show($id), |edit($id), update($request, $id)|, destroy($id)
24+
// Now we have to create the Category API
2325
Route::get('categories', [CategoryController::class, 'index']);
26+
27+
// "{category}" will use Route Model Binding
28+
Route::get('categories/{category}', [CategoryController::class, 'show']);

0 commit comments

Comments
 (0)