mergodon's avatar

Map pagination collection best practice?

Is there any better way to do something like this? I would like to pre-map some stuff in my controller, instead putting it into the view:

$articles = $articles
        ->paginate(15)
        ->appends(request()->all());

    $articles->setCollection(
        $articles->getCollection()
            ->map(function($item, $key)
            {
                $item->userstat = $item->userstats->first();
                return $item;
            })
    );

    return view('video.index', compact('articles'));
0 likes
6 replies
Ortzinator's avatar

through is basically a shortcut for @mininoz answer

/**
     * Transform each item in the slice of items using a callback.
     *
     * @param  callable  $callback
     * @return $this
     */
    public function through(callable $callback)
    {
        $this->items->transform($callback);

        return $this;
    }
3 likes

Please or to participate in this conversation.