flugg / laravel-responder

A Laravel Fractal package for building API responses, giving you the power of Fractal with Laravel's elegancy.
MIT License
861 stars 86 forks source link

Transformer not applied #178

Closed mschaefer88 closed 3 years ago

mschaefer88 commented 3 years ago

Hi!

I have currently the problem that my transformer seems not to be applied, instead the fields from the eloquent model are exposed. I'm using lumen if that's important.

My model lies within app/Models and is as follows:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * @property int id
 * @property string display_name
 */
class Gender extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'genders';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'display_name',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
    ];
}

That's the corresponding transformer:

<?php

namespace App\Transformers;

use App\Models\Gender;
use Flugg\Responder\Transformers\Transformer;

class GenderTransformer extends Transformer
{
    /**
     * List of available relations.
     *
     * @var string[]
     */
    protected $relations = [];

    /**
     * List of autoloaded default relations.
     *
     * @var array
     */
    protected $load = [];

    /**
     * Transform the model.
     *
     * @param  \App\Models\Gender $gender
     * @return array
     */
    public function transform(Gender $gender)
    {
        return [
            'id' => $gender->id,
            'name' => $gender->display_name,
        ];
    }
}

And here is the controller function:

public function index(Transformation  $transformation): array
    {
        return $transformation->make(Gender::all())->transform();
    }

Current result is:

{
 "id": 0,
  "display_name": "male"
}

And it should be according to the transformer:

{
 "id": 0,
  "name": "male"
}

I'm quite lost here and I'm thinking I might miss some cruicial point here. :-( Thanks in advance!

mschaefer88 commented 3 years ago

Sorry I was just being dumb, reread the documentation and return responder()->success(Gender::all(), GenderTransformer::class)->respond(); solved the issue.