Building relations with Laravel model factories
This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.
Often when setting up your environment for tests you'll need to generate models that require certain relations otherwise they won't work properly. Usually a view will try and access the related models and throw an error when it can't find them but sometimes your core app logic will go wonky as well.
Lucky it's now easy to lazyily build up a relationship tree for a model, whereby you can still pass through foreign keys if you need to, but if you don't then Laravel will go and new-up the required related models and associate them as you expect.
By setting the attribute to an instance of factory()
Laravel will lazily create that model as well and automatically associate it. You can do this all the way through your factories so they can manage their own dependencies.