我是Laravel Rest API的新手。在尝试教程时,出现了显示到下一条路线的链接的错误。
{
"data":{
"name":"mollitia",
"totalPrice":307.44,
"rating":5,
"href":{
"reviews":"http:\/\/127.0.0.1:8000\/api\/product\/5\/reviews"
}
}
}
我需要获得评论的href,
"reviews":"http://127.0.0.1:8000/api/products/5/reviews"
资源:
<?php
namespace App\Http\Resources\Product;
use Illuminate\Http\Resources\Json\Resource;
class ProductResource extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return [
'name' => $this->name,
'totalPrice' => round(( 1 - ($this->discount/100)) * $this->price,2),
'rating' => $this->reviews->count() > 0 ? round($this->reviews->sum('star')/$this->reviews->count(),2) : 'No rating yet',
'href' => [
'reviews' => route('reviews.index',$this->id)
]
];
}
}
我做错了什么?
答案 0 :(得分:-1)
尝试以下代码,您可以简单地扩展JsonsResource
<?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,
'totalPrice' =>round((1-($this->discount/100))* $this->price,2) ,
'raiting'=>$this->reviews->count() > 0 ? round($this->reviews->sum('star')/$this->reviews->count(),2) : 'No rating yet',
'href' =>[
'reviews'=>route('reviews.index',$this->id)
]
];
}
}