I’m using laravel framework and now I’m thinking that if laravel resource reduce the performance? Because it at first select all columns (select * from TABLE) then put the result in loop of resource. So does this loop slow down the speed?
Actually I’m think to choose between select query and resource.
User::select(['id','title'])->get() ; //or
UserResource::collection (User::all())
Which one is faster and which one is better to use and best practice? I a word I’m looking for performance and best practice Thank
2
Answers
Obviously, User::select([‘id’,’title’])->get() is faster.
If you write APIs that returns a JSON, you should use Resource because it provides more granular and robust control, such as pagination. Reference https://laravel.com/docs/10.x/eloquent-resources
So if you write APIs, you should do:
Otherwise, if controller method returns view:
Well, it is a bit hard to compare the two statements that you have provided.
The first, will result in an basic Eloquent Collection.
The second, will give you the same thing, wrapped in an API resource. Which is basically a transformer with helpers to make the entity easy to consume through an API.
So the first will probably be marginally quicker but the serve two different purposes.
Have a look at the docs:
https://laravel.com/docs/10.x/eloquent-resources
vs.
https://laravel.com/docs/10.x/eloquent-collections