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 :
Change
use Illuminate\Http\Resources\Json\ResourceCollection;
class ProductCollection extends ResourceCollection
{
to
use Illuminate\Http\Resources\Json\Resource;
class ProductCollection extends Resource
{
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)
]
];
});
}
use App\\Http\\Resources\\ProductCollection; use App\\Http\\Resources\\ProductResource; // for single collection resource in return new ProductCollection(Product::all()); //or return ProductResource::collection(Product::all()); //for single resource return new ProductResource(Product::findOrFail($id));
docs official
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.