php – 用于集合的Laravel 5.5 API资源(独立数据)

前端之家收集整理的这篇文章主要介绍了php – 用于集合的Laravel 5.5 API资源(独立数据)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道是否可以为项目资源和集合资源定义不同的数据.

对于收集我只想发送[‘id’,’title’,’slug’],但项目资源将包含额外的细节[‘id’,’slug’,’user’等]

我希望实现以下目标:

class PageResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,'title' => $this->title,'slug' => $this->slug,'user' => [
                'id' => $this->user->id,'name' => $this->user->name,'email' => $this->user->email,],];
    }
}

class PageResourceCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,];
    }
}

PageResourceCollection将无法按预期工作,因为它使用PageResource所需

return [
            'data' => $this->collection,];

我可以将资源复制到PageFullResource / PageListResource和PageFullResourceCollection / PageListResourceCollection中,但我试图找到一种更好的方法来实现相同的结果.

Resource类上有一个集合方法.您可以将其作为参数输入返回到ResourceCollection,然后在集合上指定转换.

控制器:

class PageController extends Controller
{
    public function index()
    {
        return new PageResourceCollection(PageResource::collection(Page::all()));
    }

    public function show(Page $page)
    {
        return new PageResource($page);
    }
}

资源:

class PageResource extends Resource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,];
    }
}

class PageResourceCollection extends ResourceCollection
{
    public function toArray($request)
    {
        return [
            'data' => $this->collection->transform(function($page){
                return [
                    'id' => $page->id,'title' => $page->title,'slug' => $page->slug,];
            }),];
    }
}
原文链接:https://www.f2er.com/laravel/134512.html

猜你在找的Laravel相关文章