Framework: Unable to use query builder results in Api Resource class

Created on 3 Mar 2020  路  3Comments  路  Source: laravel/framework

  • Laravel Version: 6.17.1
  • PHP Version: 7.4.2
  • Database Driver & Version: mysql & pgsql

Description:

When i use the result of a query builder and i put it in a API Resource class i get an error that the stdClass object cannot be used as an array. When i die dump the resource, it wil give me a valid resource back, but it generates an error when i want to return the resource in my controller
I've tested it with the mysql and pgsql driver, both have the same issue.

Steps To Reproduce:

Create a controller with this in it:

$builder = DB::table('users')->select('id');
return UserResource::collection($builder->paginate());

Put this in the toArray method of the UserResource:

        return [
            'id' => $this->id
        ];

Most helpful comment

Resources only work with eloquent models.

All 3 comments

Seems duplicate of #29916?

Resources only work with eloquent models.

@driesvints If resource work only with eloquent model, then why passing a Illuminate\Database\Eloquent\Collection Model::all() is transformed into a Illuminate\Support\Collection Resource and therefore breaking behaviour like the following.

this works

$categories = Category::get();
$categories->append('hierarchicalName');
$collection = CategoryResource::collection($categories);

this doesn't

$categories = Category::get();
$collection = CategoryResource::collection($categories);
$collection->append('hierarchicalName');

A solution would be to create a ModelResourceCollection and extend de framework's behaviour but this doesn't sound like future proof to me.

Would such a class be helpful?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gabriellimo picture gabriellimo  路  3Comments

YannPl picture YannPl  路  3Comments

felixsanz picture felixsanz  路  3Comments

RomainSauvaire picture RomainSauvaire  路  3Comments

kerbylav picture kerbylav  路  3Comments