Simplify Factory Associations with Laravel's UseFactory Attribute
Last updated on by Harris Raftopoulos

Laravel introduces the UseFactory attribute, providing a declarative approach to associate factories with Eloquent models. This PHP 8.0+ attribute feature creates clearer, more elegant factory connections, especially valuable for models outside standard naming conventions.
Traditionally, factory registration in Laravel required either strict adherence to naming conventions or manual factory method definitions. The UseFactory attribute streamlines this process by allowing direct factory specification on your model classes:
use Database\Factories\ArticleFactory;use Illuminate\Database\Eloquent\Attributes\UseFactory; #[UseFactory(ArticleFactory::class)]class Article extends Model{ use HasFactory;}
This approach particularly shines in domain-driven or module-based architectures:
// Article modelnamespace App\Domains\Content\Models; use Database\Factories\ArticleFactory;use Illuminate\Database\Eloquent\Attributes\UseFactory;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\HasMany; #[UseFactory(ArticleFactory::class)]class Article extends Model{ use HasFactory; protected $fillable = ['title', 'body', 'published_at']; #[UseFactory(CommentFactory::class)] public function comments(): HasMany { return $this->hasMany(Comment::class); }} // Subscription modelnamespace App\Domains\Billing\Models; #[UseFactory(SubscriptionFactory::class)]class Subscription extends Model{ use HasFactory; // No need for newFactory() method or $model property // The factory association is handled by the attribute}
The UseFactory attribute offers several advantages over traditional methods. It creates a visible, explicit connection between models and factories while maintaining compatibility with existing approaches. Laravel follows a clear resolution priority when determining which factory to use:
- Static $factory property if defined
- UseFactory attribute if present
- Convention-based factory resolution
This attribute acts as a decorator for your models, clearly indicating the associated factory without requiring additional method definitions or rigid naming conventions.
Using the attribute also improves IDE support and code readability by making factory relationships immediately apparent to developers reading the model code:
namespace App\Modules\Inventory\Models; use Database\Factories\ProductVariantFactory;use Illuminate\Database\Eloquent\Attributes\UseFactory; #[UseFactory(ProductVariantFactory::class)]class ProductVariant extends Model{ use HasFactory; // Factory relationship is clearly visible at the class level // improving discoverability and maintainability}
The UseFactory attribute represents Laravel's commitment to leveraging modern PHP features for more expressive, maintainable code patterns.