Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to use query builder results in Api Resource class #31703

Closed
kevinpijning opened this issue Mar 3, 2020 · 3 comments
Closed

Unable to use query builder results in Api Resource class #31703

kevinpijning opened this issue Mar 3, 2020 · 3 comments

Comments

@kevinpijning
Copy link

  • 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
        ];
@LastDragon-ru
Copy link
Contributor

LastDragon-ru commented Mar 3, 2020

Seems duplicate of #29916?

@driesvints
Copy link
Member

Resources only work with eloquent models.

kevinpijning added a commit to kevinpijning/framework that referenced this issue Mar 3, 2020
Restores php 7.4 compatibility for paginator resources that receives objects (for example from the query builder) instead of models.

Fixes laravel#31703 and  laravel#29916
@f-ricci
Copy link

f-ricci commented Jun 6, 2020

@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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants