Skip to content

Conversation

Lukasss93
Copy link
Contributor

This PR adds the possibility to define resource classes directly on a model using PHP attributes.

Background

Right now, toResource and toResourceCollection automatically resolve the resource class only if it follows the <ModelName>Resource naming convention.

In my project, I couldn’t follow the naming convention for resources.
As a result, I need to write calls like this everywhere:

$model->toResource(MyCustomNameResource::class);
$collection->toResourceCollection(MyCustomNameCollectionResource::class);

This gets repetitive and makes the code less clean.

What’s New

With this PR, developers can declare attributes on the model and let Laravel handle the resource resolution automatically:

use App\Http\Resources\MyCustomNameResource;
use App\Http\Resources\MyCustomNameCollectionResource;

#[UseResource(MyCustomNameResource::class)]
#[UseResourceCollection(MyCustomNameCollectionResource::class)]
class MyModel extends Model {}

Now you can simply call:

$model->toResource();
$collection->toResourceCollection();

@taylorotwell taylorotwell merged commit 6a90969 into laravel:12.x Sep 10, 2025
63 checks passed
@Lukasss93 Lukasss93 deleted the use-resource-attributes branch September 15, 2025 12:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants