Api: Array Transformer is not working

Created on 5 Apr 2017  路  3Comments  路  Source: dingo/api

Hello,

I got this error if I try to transform array

Type error: Argument 1 passed to Dingo\Api\Http\Response\Factory::collection() must be an instance of Illuminate\Support\Collection, array given, called in ....

My Transformer

<?php
namespace App\Transformers;

use League\Fractal\TransformerAbstract;

class ArrayTransformer extends TransformerAbstract
{
    public function transform(Array $model){
        return [
            'name' => $model
        ];
    }
}

My Controller

        $arr = [
              "lorem",
              "Ipsum",
              "Test"
            ];
    $this->response->collection($arr, new ArrayTransformer, ['key'=>'test']);

Most helpful comment

The error is in your code, not in the package. Read the error again and your code.

All 3 comments

The error is in your code, not in the package. Read the error again and your code.

There is an error with the example code provided as it does not match the expected Collection. But even if you wrap the array inside a \Illuminate\Support\Collection it will crash here https://github.com/dingo/api/blob/v3.0.5/src/Http/Response/Factory.php#L101 because it expects an object type.

Is there a specific reason we force the use of objects in collections inside Dingo/Api. Is the wanted behavior or is it a bug or limitation? Fractal seems to support array out of the box, so why shouln't Dingo?
https://fractal.thephpleague.com/simple-example/

The way transformation works, everything must be an object, that's why dingo wraps it in Stdclass.

If you have in your code in using dingo something not working which it should, please post it in a new issue and we'll take a look.

Closing this ticket as it's several years old.

Was this page helpful?
0 / 5 - 0 ratings