ProductController.php
class ProductController extends Controller
{
public function index(Request $request)
{
$limit = $request->has('limit') ? $request->get('limit') : 10;
$offset = $request->has('offset') ? $request->get('offset') : 0;
$products = Product::offset($offset)->limit($limit)->get();
return new ProductResource($products);
}
//Search Products
public function search($name, Request $request)
{
$limit = $request->has('limit') ? $request->get('limit') : 10;
$offset = $request->has('offset') ? $request->get('offset') : 0;
$products = Product::where('name', 'like', '%' . $name . '%')
->offset($offset)->limit($limit)->get();
return new ProductResource($products);
}
}
ProductResource.php
class ProductResource extends JsonResource
{
public function toArray($request)
{
foreach ($request->all() as $product) {
$response = [
'id' => "p" . $product->id,
'name' => $product->name,
'slug' => $product->slug,
'regular_price' => $product->regular_price,
'sale_price' => $product->sale_price,
'SKU' => $product->SKU,
'stock_status' => $product->stock_status,
'quantity' => "p" . "$product->quantity",
'image' => $product->url,
'images' => $product->url,
'category_id' => $product->category_id,
];
$responses[] = $response;
}
return response($responses, 201);
}
}
This is my get route from api (http://127.0.0.1:8000/api/products?limit=5&offset=0) when send, "message": "Attempt to read property "id" on string", "file": "/Applications/XAMPP/xamppfiles/htdocs/DNI_E_commerce/app/Http/Resources/ProductResource.php", "line": 20,
CodePudding user response:
In your Search function, you can just return $products that you get from your ->get() query. $products is a laravel collection of all the products matching the search query in the DB. A collection is basically a fancy object. https://laravel.com/docs/8.x/eloquent-collections
If you do that, you should be able to use the toArray() function as is, but you can also just loop through the collection without making it into an array first.