我正在尝试使用Laravel的资源集合转换所有产品的json数据。但这会引发错误。
“此集合实例上不存在属性[名称]”。
我检查了官方文档,他们以类似的方式实施了该文档。
ProductController.php
public function index()
{
return new ProductCollection(Product::all());
}
ProductCollection.php
namespace App\Http\Resources\Product;
use Illuminate\Http\Resources\Json\ResourceCollection;
class ProductCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'name' => $this->name,
'price' => $this->price
];
}
}
ProductResource.php
namespace App\Http\Resources\Product;
use Illuminate\Http\Resources\Json\JsonResource;
class ProductResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'name' => $this->name,
'description' => $this->detail,
'price' => $this->price,
'stock' => $this->stock,
'discount' => $this->discount,
'effectivePrice' => round($this->price * (1 - ($this->discount/100)), 2),
'rating' => $this->reviews->count() > 0 ? round($this->reviews->sum('star') / $this->reviews->count(), 2) : 'No Ratigs Yet',
'href' => [
'reviews' => route('reviews.index', $this->id)
]
];
}
}
注意:在不转换ProductCollection时,即当ProductCollection的toArray()函数如下所示时,工作正常:
public function toArray($request)
{
return parent::toArray($request);
}
最佳答案
ProductCollection
用于Products
的集合。
因此,您需要使用foreach。
class ProductCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
// final array to be return.
$products = [];
foreach($this->collection as $product) {
array_push($products, [
'name' => $product->name,
'price' => $product->price
]);
}
return $products;
}
}