Skip to content

Commit

Permalink
Update Seeder docs with Factory States example
Browse files Browse the repository at this point in the history
  • Loading branch information
drbyte committed Jan 14, 2024
1 parent 16b8b47 commit 9b02e54
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions docs/advanced-usage/seeding.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ You can optionally flush the cache before seeding by using the `SetUp()` method

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

## Roles/Permissions Seeder

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):

```php
Expand Down Expand Up @@ -54,6 +56,42 @@ class RolesAndPermissionsSeeder extends Seeder
}
```

## User Seeding with Factories and States

To use Factory States to assign roles after creating users:

```php
// Factory:
public function definition() {...}

public function active(): static
{
return $this->state(fn (array $attributes) => [
'status' => 1,
])
->afterCreating(function (User $user) {
$user->assignRole('ActiveMember');
});
}

// Seeder:
// To create 4 users using this 'active' state in a Seeder:
User::factory(4)->active()->create();
```

To seed multiple users and then assign each of them a role, WITHOUT using Factory States:

```php
// Seeder:
User::factory()
->count(50)
->create()
->each(function ($user) {
$user->assignRole('Member');
});
```


## Speeding up seeding for large data sets

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).
Expand Down

0 comments on commit 9b02e54

Please sign in to comment.