Introduces UseFactory attribute#54065
Conversation
|
I think I'm on board overall. Any reason you didn't just choose |
|
@taylorotwell No particular reason other than for an explicit name to tell the developer exactly what it does, and to follow a more action-focused naming convention of the other attributes, e.g. Also, probably just React leaking into my brain 😅 |
|
One might name it |
|
@taylorotwell Would you like me to change to |
|
Hmm, got it. Good point on ScopedBy, etc. I would probably name this |
Well, it's possible—it could just end up being a PITA to keep in mind to alias one of them 😂 |
|
@taylorotwell Yeah that was my conclusion as well. Which, is how I arrived at Naming is hard! |
|
I was thinking it could be named as <?php
namespace App\SomeFeatureDomain\Models\Comment;
use Database\Factories\CommentFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Attributes\CreateFactoryUsing;
#[CreateFactoryUsing(CommentFactory::class)]
class Comment extends Model
{
use HasFactory;
// ...
} |
|
@Rizky92 another good suggestion! Just waiting to see where we land from the maintainers, and I'll be happy to update the name to whatever we land on. This will be my first contribution to core so, hoping it gets in 🤞🥹 |
|
How about getting rid of the trait call as well? why should we need to define both the trait and the attribute |
|
I noticed that I still need to add |
|
@raz-iacob @stsepelin Noted, I'll try and reproduce and fix stan 👍 |
|
@christopherarter Is there an update for this with phpstan/larastan? |
It's the Laravel Idea issue laravel-idea/plugin#1220 |


Description
This PR introduces a new UseFactory attribute that provides a more elegant way to associate model factories with Eloquent models using PHP 8.0+ attributes. This is especially useful for factory registration for models that are outside of the typical
App\Modelsnamespace and improves code readability (in my opinion).Usage
Instead of defining a new method for
newFactory(), we can simply allow developers to add the Attribute.Automatic inverse detection
When using this attribute, the factory for the given model will automatically be set, so there is no need to define a
protected $model = \App\SomeFeatureDomain\Models\Comment::classfrom our example above.Completely Optional & Fully backwards compatible
This logic only runs on classes that implement this attribute. Developers are still free to define static
newFactorymethods as they have before.Priority Order
The factory resolution follows this priority:
$factoryproperty if definedUseFactoryattribute if presentRequirements
Testing
This PR includes tests that verify: