Skip to content

Commit 9b02e54

Browse files
authored
Update Seeder docs with Factory States example
1 parent 16b8b47 commit 9b02e54

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

docs/advanced-usage/seeding.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ You can optionally flush the cache before seeding by using the `SetUp()` method
1818

1919
Or it can be done directly in a seeder class, as shown below.
2020

21+
## Roles/Permissions Seeder
22+
2123
Here is a sample seeder, which first clears the cache, creates permissions and then assigns permissions to roles (the order of these steps is intentional):
2224

2325
```php
@@ -54,6 +56,42 @@ class RolesAndPermissionsSeeder extends Seeder
5456
}
5557
```
5658

59+
## User Seeding with Factories and States
60+
61+
To use Factory States to assign roles after creating users:
62+
63+
```php
64+
// Factory:
65+
public function definition() {...}
66+
67+
public function active(): static
68+
{
69+
return $this->state(fn (array $attributes) => [
70+
'status' => 1,
71+
])
72+
->afterCreating(function (User $user) {
73+
$user->assignRole('ActiveMember');
74+
});
75+
}
76+
77+
// Seeder:
78+
// To create 4 users using this 'active' state in a Seeder:
79+
User::factory(4)->active()->create();
80+
```
81+
82+
To seed multiple users and then assign each of them a role, WITHOUT using Factory States:
83+
84+
```php
85+
// Seeder:
86+
User::factory()
87+
->count(50)
88+
->create()
89+
->each(function ($user) {
90+
$user->assignRole('Member');
91+
});
92+
```
93+
94+
5795
## Speeding up seeding for large data sets
5896

5997
When seeding large quantities of roles or permissions you may consider using Eloquent's `insert` command instead of `create`, as this bypasses all the internal checks that this package does when calling `create` (including extra queries to verify existence, test guards, etc).

0 commit comments

Comments
 (0)