Performance: Resource collections
This affects the server response time and the size of data sent to the client, impacting page load speed and perceived responsiveness.
Jump into concepts and practice - no test required
return UserResource::collection(User::paginate(15));
return User::all();| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Returning raw large dataset | N/A (server-side) | N/A | High due to large JSON parsing | [X] Bad |
| Using paginated resource collection | N/A (server-side) | N/A | Low due to smaller JSON | [OK] Good |
::collection() in Laravel resource classes?::collection() does::collection() method wraps multiple model instances to apply the resource formatting to each item.::collection() wraps many models for consistent output [OK]::collection() with single model resource$users using a resource class UserResource?::collection() on the resource class with the collection as argument.UserResource::collection($users); which is correct. Other options either create a single resource or use invalid methods.::collection() for multiple items, not new [OK]new UserResource($users) for collectionsall() or make()return UserResource::collection($users)->additional(['meta' => ['total' => $users->count()]]);
additional() method usageadditional() method adds extra data (like meta info) to the resource collection response.data key with formatted users and a meta key with the total count from additional().additional() adds extra keys outside 'data' [OK]return UserResource::collection()->additional(['status' => 'success']);
collection()collection() method requires a collection or array argument to wrap. Here it is called without any argument.additional() can be used on collections and accepts an array. Using new UserResource() is for single models, not collections.collection() -> Option Acollection() needs argument [OK]collection() [OK]collection() without dataadditional() is invalid on collectionsmeta key. Which code snippet correctly achieves this?paginate(10) on the query to get a paginator instance. Pass this to collection().currentPage(), it must be called on the paginator returned by paginate(), not on the original query builder $posts.$posts->paginate(10)->currentPage() within additional() correctly retrieves the current page from a paginator instance, ensuring the paginated data and meta align.