简体   繁体   中英

Laravel API ResourceCollection doesnt works

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)
            ]
        ];
    });
}

create two resources

for single resource and collection resource

  • php artisan make:resource ProductResource
  • php artisan make:resource ProductCollection or
  • php artisan make:resource Product --collection

then go to your controller

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM