Fractal Laravel

So what i need was an simple api with pagination, found this package https://github.com/spatie/laravel-fractal the documentation was not quite simple so had little research. In this example I'm using article, so first create Transformer folder.

<?php
namespace App\Transformers;

use App\Article;
use League\Fractal\TransformerAbstract;

class ArticleTransformer extends TransformerAbstract
{
    public function transform(Article $article)
    {
        return [
            'title' => $article->title,
            'description' => $article->description
        ];
    }
}

Then in the Api Controller

<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Article;
use App\Http\Controllers\Controller;

use App\Transformers\ArticleTransformer;
use League\Fractal\Manager;
use League\Fractal\Resource\Collection;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;

class ArticleController extends Controller
{

    /**
     * @var Manager
     */
    private $fractal;

    /**
     * @var UserTransformer
     */
    private $articleTransformer;

    function __construct(Manager $fractal, ArticleTransformer $articleTransformer)
    {
        $this->fractal = $fractal;
        $this->articleTransformer = $articleTransformer;
    }

    public function index() {
        $articlesPaginator = Article::paginate(10);
        $articles = new Collection($articlesPaginator->items(), $this->articleTransformer);
        $articles->setPaginator(new IlluminatePaginatorAdapter($articlesPaginator));
        $articles = $this->fractal->createData($articles); // Transform data
        return $articles->toArray();
    }
}

Then the result should be like this

Subscribe to You Live What You Learn

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe