i would like to know how to get work API call with ResourceCollection
Error :
Undefined property: Illuminate\Database\Query\Builder::$name
my product method :
public function index()
{
return ProductCollection::collection(Product::all());
}
my collection :
public function toArray($request)
{
//return parent::toArray($request);
return [
"name" => $this->name,
"price" => $this->price,
"href" => [
"link" => route("product.show", $this->id)
]
];
}
tryed it just by Resourse ( not ResourceCollection ) just modifed method call and its was working but i need know how to fix ResourceCollection return new ProductResource($product);
error snap :
ProductCollection inherits ResourceCollection and not a Resource, so $this is not the model but the collection. If you want to mutate each element of the collection you can use the map function like that:
public function toArray($request)
{
return $this->map(function($product) {
return [
"name" => $this->name,
"price" => $this->price,
"href" => [
"link" => route("product.show", $this->id)
]
];
});
}