Skip to content

Commit 4f5472f

Browse files
author
ahmadhuss
committed
feat: Api/ProductController Resource and api route has been added
1 parent e698cd6 commit 4f5472f

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
}

routes/api.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<?php
22

33
use App\Http\Controllers\Api\CategoryController;
4+
use App\Http\Controllers\Api\ProductController;
45
use Illuminate\Http\Request;
56
use Illuminate\Support\Facades\Route;
67

@@ -26,3 +27,9 @@
2627

2728
// "{category}" will use Route Model Binding
2829
Route::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']);

0 commit comments

Comments
 (0)