Laravel API Resource Generator
Generate Laravel JsonResource and ResourceCollection classes with field mappings, conditional relations, and metadata.
Singular CamelCase, e.g. Post, User, Product
Auto-filled as {Model}Resource.
Leave empty for no wrapping.
Map each API response key to an expression. Supports $this->attribute, $this->relation->field, and helpers.
Relations that should only appear when they have been eager-loaded (whenLoaded).
Optional JSON object for the with() method. Used in collection for pagination links/meta.
How to Use the Laravel API Resource Generator
This tool helps you create Laravel API Resource and Resource Collection classes. Follow these steps:
- Enter the model name — Type a singular CamelCase name like
Post. The resource class name auto-fills. - Define field mappings — Add rows mapping each API response key to a
$this->attributeor expression. - Add conditional relations — Use
whenLoadedto include relations only when eager-loaded. - Configure metadata — Add
with()metadata and pagination links for collections. - Generate — Click Generate Resource to create the PHP class(es).
- Copy or Download — Click Copy or Download to save as
{Model}Resource.php.
Frequently Asked Questions
What is an API Resource in Laravel?
API Resources are classes that transform your Eloquent models and collections into JSON responses. They live in app/Http/Resources/ and provide a clean way to shape API output, hide attributes, include relationships, and add metadata.
What is the difference between Resource and ResourceCollection?
Resource (extends JsonResource) transforms a single model instance. ResourceCollection (which also extends JsonResource) transforms a collection of models, often with pagination links and metadata.
What does whenLoaded() do?
whenLoaded('relation') includes the field only if the relation has been eager-loaded. This prevents N+1 queries while still allowing the resource to include relation data when available.
Should I wrap my resource in a data key?
Laravel wraps resource responses in a data key by default, because JsonResource::$wrap is 'data'. Keep the Wrap Key set to data when your client expects that envelope. Leaving it empty omits the property, so the class still inherits the default wrapper; to return a bare array, call JsonResource::withoutWrapping() once in a service provider.
Why does the output contain two classes?
The form has "Generate Resource Collection" enabled by default, so the tool prints PostResource and PostCollection together for convenience. Laravel expects one class per file: save the first half as app/Http/Resources/PostResource.php and the second as app/Http/Resources/PostCollection.php. The combined output is valid PHP, but the autoloader looks up files by class name.
Does whenLoaded() prevent N+1 queries?
Not by itself. whenLoaded() only hides a relation when it has not been loaded, so the response stays clean. The query count is decided in your controller: use Post::with('author') or $post->load('author') to fetch relations in a fixed number of queries. For counts, combine withCount('comments') with whenCounted('comments').
How do I remove the data wrapper?
Call JsonResource::withoutWrapping() once in AppServiceProvider::boot() to return bare arrays. You can also leave the Wrap Key blank in this tool, which simply omits the property — but the class then inherits the default data wrapper. Note that $wrap is a static property, so the generated line is public static $wrap = "data"; — a non-static declaration would be a fatal error.
What make:resource Generates
Laravel can scaffold the class before you add a single field. php artisan make:resource PostResource writes app/Http/Resources/PostResource.php. The --collection flag — or a name ending in Collection, as in make:resource PostCollection — writes a ResourceCollection instead. A third variant, --json-api, generates the JSON:API shape with attributes(), relationships(), and links() methods; this page produces the simpler toArray() form.
The stock stub extends JsonResource and returns parent::toArray($request), which exposes every model attribute — including columns you may not want in a public API:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class PostResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return parent::toArray($request);
}
}
Each field row in this tool becomes one entry in that returned array, so the generator is a faster way to write the body you would otherwise type by hand. A relation row becomes a whenLoaded() call. Class names follow the Artisan convention: a singular CamelCase model goes in, PostResource comes out, and the collection is named PostCollection. Keep those suffixes if you split the output into separate files — Laravel reads the name to decide which resource a collection maps.
Single Resources vs Collections
A resource answers one question: what does this record look like as JSON? Wrap a single model with new PostResource($post) or the static shortcut PostResource::make($post) and the response is one object under the default data key:
{
"data": {
"id": 1,
"title": "Hello world",
"author": { "id": 7, "name": "Ada" },
"created_at": "2026-11-14T09:00:00.000000Z"
}
}
A collection applies the same transformation to many records. PostResource::collection($posts) returns an anonymous collection that maps every item through PostResource; the generated PostCollection is the named version, useful when you want to add metadata or customise the pagination envelope. If the collection class is not named after its resource, declare the link explicitly with public $collects = PostResource::class;.
When the value you pass is a paginator, Laravel adds links and meta beside data. A plain Collection or array does not:
{
"data": [ { "id": 1, "title": "Hello world" } ],
"links": {
"first": "https://example.test/api/posts?page=1",
"last": "https://example.test/api/posts?page=3",
"prev": null,
"next": "https://example.test/api/posts?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 3,
"path": "https://example.test/api/posts",
"per_page": 15,
"to": 15,
"total": 42
}
}
That is why the tool has a separate Include pagination links option: the generated collection reads currentPage(), lastPage(), perPage(), and total() from the underlying paginator, so only enable it when the collection will receive one.
Conditional Relationships Without N+1 Queries
The relation rows exist to keep one response shape for several endpoints. A post list may not need comments, while a single-post endpoint does. whenLoaded('comments') includes the key only when the relation is already loaded; otherwise it returns a MissingValue that is filtered out of the final array. The field does not lazy-load and does not run a query on its own.
// app/Http/Controllers/Api/PostController.php
public function index()
{
return PostResource::collection(
Post::with('author')->paginate(15)
);
}
public function show(Post $post)
{
$post->load('author', 'comments');
return new PostResource($post);
}
The query count is decided in the controller. Without with('author'), a 15-post page runs one query for the posts and then one per post for the author — the classic N+1 pattern. With eager loading it runs exactly two. whenLoaded() then keeps the JSON honest: a relation that was not requested simply does not appear.
For counts, the same idea has a shorter form. Post::withCount('comments') adds a comments_count attribute in the same query, and $this->whenCounted('comments') exposes it only when present. Loading the full relation to count it is the expensive alternative.
The generator writes single-relation expressions as new UserResource($this->author). For a hasMany, pass a collection resource instead — CommentResource::collection($this->comments) — because wrapping a collection in a single resource produces one object where the client expects an array.