File tree Expand file tree Collapse file tree 3 files changed +71
-0
lines changed
Expand file tree Collapse file tree 3 files changed +71
-0
lines changed Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace App \Http \Controllers \Api ;
4+
5+ use App \Http \Controllers \Controller ;
6+ use App \Http \Resources \ProductResource ;
7+ use App \Models \Product ;
8+ use Illuminate \Http \Request ;
9+
10+ class ProductController extends Controller
11+ {
12+ // We want category object also so that's why we have created the relationship
13+ // So our query will be use `with()` which help us to return the relationship too.
14+ public function index () {
15+ $ products = Product::with ('category ' )->get ();
16+ // return $products;
17+ return ProductResource::collection ($ products );
18+ }
19+
20+
21+ public function show (Product $ product ) {
22+ return new ProductResource ($ product );
23+ }
24+ }
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ namespace App \Http \Resources ;
4+
5+ use Illuminate \Http \Resources \Json \JsonResource ;
6+
7+ class ProductResource extends JsonResource
8+ {
9+ /**
10+ * Transform the resource into an array.
11+ *
12+ * @param \Illuminate\Http\Request $request
13+ * @return array
14+ */
15+ public function toArray ($ request )
16+ {
17+ // Either we can use this approach or we can use approach number 2
18+ /*
19+ return [
20+ 'id' => $this->id,
21+ 'name' => $this->name,
22+ 'category' => [
23+ 'id' => $this->id,
24+ 'name' => $this->name,
25+ ],
26+ 'price' => $this->price,
27+ 'description' => $this->description,
28+ ];*/
29+
30+ // Approach no 2: use resource inside the resource
31+ return [
32+ 'id ' => $ this ->id ,
33+ 'name ' => $ this ->name ,
34+ 'category ' => new CategoryResource ($ this ->category ),
35+ 'price ' => $ this ->price ,
36+ 'description ' => $ this ->description ,
37+ ];
38+
39+ }
40+ }
Original file line number Diff line number Diff line change 11<?php
22
33use App \Http \Controllers \Api \CategoryController ;
4+ use App \Http \Controllers \Api \ProductController ;
45use Illuminate \Http \Request ;
56use Illuminate \Support \Facades \Route ;
67
2627
2728// "{category}" will use Route Model Binding
2829Route::get ('categories/{category} ' , [CategoryController::class, 'show ' ]);
30+
31+
32+ // Product API
33+ Route::get ('products ' , [ProductController::class, 'index ' ]);
34+ // "{product}" will use Route Model Binding
35+ Route::get ('products/{product} ' , [ProductController::class, 'show ' ]);
You can’t perform that action at this time.
0 commit comments