Summer Sale! All accounts are 50% off this week.

CLab's avatar
Level 3

Laravel 8 factory attach relationship after creating

I am creating a factory for a model Post for testing. I have a seed for set tags already in the database. I want to be able to attach Tags (polymorphic many-to-many relationship) to a post automatically after creating it.

How can I do that in the PostFactory class, so that when a post is created, it is automatically attached with some tags?

Note- my classes are not exactly Posts and Tags but something else - I have just abstracted them for the purposes of relating to examples found commonly in Laravel.

0 likes
4 replies
CLab's avatar
Level 3

@Nakov Thanks Nakov I saw this - but how does one actually use the instance of the post being created to attach the tag to?

In the example provided they used:

return $this->afterMaking(function (User $user) {
            //
        })->afterCreating(function (User $user) {
            //
        });

so would it be something like $user->attach($roles)?

Nakov's avatar

@CLab no, if you define the callbacks in the PostFactory, then it will be Post whats passed in:

return $this->afterMaking(function (Post $post) {
            //
        })->afterCreating(function (Post $post) {
            //
        });

That's just an example from the docs. You use it for your needs.

CLab's avatar
Level 3

@Nakov Yes I understand replace User $user with the model you are working with. Thanks this works.

Please or to participate in this conversation.