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.
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
];
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?
Most helpful comment
Resources only work with eloquent models.