user13997067
user13997067

Reputation:

Laravel resources - how does it work exactly?

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);
        }

Upvotes: 0

Views: 747

Answers (2)

Basheer Kharoti
Basheer Kharoti

Reputation: 4302

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

Upvotes: 0

Netanel Prins
Netanel Prins

Reputation: 11

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

Upvotes: 1

Related Questions