skip to Main Content

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


  1. 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:

    return UserResource::collection(User::select(['id','title'])->get()); 
    

    Otherwise, if controller method returns view:

    $users = User::select(['id','title'])->get();
    return view('users.index', compact('users'));
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search