Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
749 views
in Technique[技术] by (71.8m points)

laravel - Return different data for 2 different routes from the same model using API resource

I have 2 routes which hits show() & index() method in controller. The model name is Feed & has 4 relations FeedType, FeedImage, FeedVideo & FeedCaption.

I m returning all the fields & specific relations fields except 'thumbnail' field through the Feed resource when API hits show() method

class Feed extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  IlluminateHttpRequest  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->content,
            'keywords' => $this->keywords,
            'slug' => $this->slug,
            'type' => new FeedTypeResource($this->feedType),
            'images' => FeedImageResource::collection($this->feedImages),
            'video' =>  new FeedVideoLinkResource($this->feedVideoLink),
            'caption' => new FeedCaptionResource($this->feedCaption),
        ];
    }
}

Now I want to return only 3 fields 'title', 'thumbnail', 'created_at' with one relation field 'name' from FeedType relation through a resource when API hits show() method. So I created a FeedCollection resource. But it is giving error.

class FeedCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  IlluminateHttpRequest  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'title' => $this->title,
            'thumbnail' => $this->thumbnail,
        ];
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use chunk method for collection. The chunk method breaks the collection into multiple, smaller collections of a given size:

$collection = collect([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection->chunk(4);

$chunks->all();

// [[1, 2, 3, 4], [5, 6, 7]]

This method is especially useful in views when working with a grid system such as Bootstrap. For example, imagine you have a collection of Eloquent models you want to display in a grid:

@foreach ($products->chunk(3) as $chunk)
    <div class="row">
        @foreach ($chunk as $product)
            <div class="col-xs-4">{{ $product->name }}</div>
        @endforeach
    </div>
@endforeach

please see examples from the link: https://laravel.com/docs/8.x/collections#method-chunk


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...