logo
podcast Podcast
get help Get Unstuck

One reason to create a factory for a model you don't own

Always thinking about readability

Joel Clermont
Joel Clermont
2025-07-03

Factories make it really easy to generate data for your tests, but have you ever considered creating a factory for an Eloquent model you didn't write? For example, a model that comes from a package you installed?

Honestly, I had never considered this, but I saw Aaron do it on a recent project, and I really liked the idea.

The package was Laravel Auditing and the factory was for the Audit model it provides.

We ran into a bug where a model generated audit records, but then was later soft-deleted. When that audit record was later displayed as part of a historical log, it would throw an error because the model was no longer available.

This was easy enough to fix, but anytime we hit a bug, we like to add a test to ensure it doesn't happen again.

For our test setup we could have created a model, made changes to it which would fire audit events, then soft-delete the model. But instead, Aaron created a factory for the Audit model, which allowed us to generate audit records directly, making it very clear exactly what was being tested.

This was a simple solution that keeps our tests more readable, and gives us the expressiveness of factory states that we're used to using.

One additional thing I liked about his implementation was he prefixed the factory name with the package namespace, so instead of AuditFactory, it was OwenItAuditFactory. This is a nice reminder that this factory is for a model that comes from a package, and not one we wrote ourselves.

Here to help,

Joel

P.S. Would you like a set of Laravel experts to review your code and give suggestions where you can improve? Schedule a call to get started.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.