File tree Expand file tree Collapse file tree 2 files changed +8
-2
lines changed
Expand file tree Collapse file tree 2 files changed +8
-2
lines changed Original file line number Diff line number Diff line change 33namespace App \Http \Controllers \Api ;
44
55use App \Http \Controllers \Controller ;
6+ use App \Http \Resources \CategoryResource ;
67use App \Models \Category ;
78use Illuminate \Http \Request ;
89use Illuminate \Http \Resources \Json \ResourceResponse ;
@@ -17,13 +18,14 @@ public function index(){
1718
1819 // Route model binding
1920 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+ // return $category; // It will return category as a JSON response object and it is the magic of Laravel
2122
2223 // It is difficult to return only id and name with the Route model binding
2324 // There are only 2 ways:
2425 // 1.Either you can use collection methods to filter
2526 // 2.But now it is time to introduce API resources which will contain set of rules for the API.
2627 // php artisan make:resource CategoryResource
28+ return new CategoryResource ($ category );
2729 }
2830
2931
Original file line number Diff line number Diff line change @@ -14,6 +14,10 @@ class CategoryResource extends JsonResource
1414 */
1515 public function toArray ($ request )
1616 {
17- return parent ::toArray ($ request );
17+ // In this method we have to override the results.
18+ return [
19+ 'id ' => $ this ->id ,
20+ 'name ' => $ this ->name
21+ ];
1822 }
1923}
You can’t perform that action at this time.
0 commit comments