[請益] laravel API resource

作者: gonjay (gon)   2018-03-25 00:14:44
目前我建立了一個 resource 來轉換 model 的輸出資料格式,在 controller 中有兩個方法的返回值會使用到這個 resource,但是我想讓不同方法使用這個 resource 時,可以返回不同的資料,比如 index 方法只返回 id, st
程式碼大約如下(有稍微修改)
Resource :
class testResource extends Resource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name
];
}
}
Controller 中的方法:
use testResource;
public function index()
{
{
{
$test = Test::paginate(10);
$this->response(testResource::collection($test);
}
public function store()
{
$test = Test::find(1):
$this->response(new testResource($test));
}
作者: DongFeng   2018-03-25 00:22:00
paginate跟find的查詢結果就已經是不一樣的物件了,有什麼一定要使用同一個method的理由嗎?
作者: ChenCH1986 (Chen,C.H.)   2018-03-25 21:08:00
Transformer
作者: DongFeng   2018-03-25 23:42:00
https://github.com/logaretm/transformers/blob/master/README.md我覺得上面這個套件應該可以達到你想要的效果看一下 Alternate Transformations 這個章節

Links booklink

Contact Us: admin [ a t ] ucptt.com