0

When I create an api and use laravel resources, is it better to get the full data and then choose which columns to send in the resource file, or maybe when selecting data from the database, determine which columns should be selected?

1)

return UserResource::collection(User::all());

// Resource file:
public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name
        ];
    }
return UserResource::collection(User::all('id', 'name'));

// Resource file:
    public function toArray($request)
        {
            return parent::toArray($request);
        }

2 Answers2

1

It's always better practice to load only the relevant data, because it saves memory and time. In laravel you can easily accomplish that in the query using the "select" function e.g

return UserResource::collection(User::select('id', 'name')->get());

// Resource file:
    public function toArray($request)
        {
            return parent::toArray($request);
        }

https://laravel.com/docs/7.x/queries#selects

How to select specific columns in laravel eloquent

  • From what I noticed - this example also works. Is it correct? User::all('id', 'name') –  Aug 09 '20 at 07:51
  • Yes. "all" function accepts parameters, but uses laravel collection. Query builder is always faster (https://laracasts.com/discuss/channels/eloquent/all-vs-get-laravel-eloquent). I think you are looking for this - User::select('id', 'name')->get()->toArray(); – Netanel Prins Apr 24 '21 at 11:55
0

If you have millions of records in the database, I would definitely recommend fetching specific columns from the table. Here are some of the stats that I run over table with 36K records

SELECT *  from `app_logs` // + 0.172 sec
SELECT ID FROM `app_logs`// + 0.016 sec

So the difference is enough even with just few thousands records.

However, for the simplicity and not concerning the performance, you can use the laravel fancy syntax as well

User::all()

Check @Marc_S answer on why you should select only required columns

Basheer Kharoti
  • 4,202
  • 5
  • 24
  • 50