简体   繁体   中英

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

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 eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM