Skip to content

Commit 132769b

Browse files
author
ahmadhuss
committed
refactor: Getting Single Category with only id & name
1 parent 87bb0e3 commit 132769b

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

app/Http/Controllers/Api/CategoryController.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace App\Http\Controllers\Api;
44

55
use App\Http\Controllers\Controller;
6+
use App\Http\Resources\CategoryResource;
67
use App\Models\Category;
78
use Illuminate\Http\Request;
89
use 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

app/Http/Resources/CategoryResource.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)