---
title: "Random cases & factories — Enums for Laravel | Roundly"
description: "random() picks a random case for model factories, seeders and demo data; collect() walks every case."
url: https://roundly-consulting.com/open-source/docs/enums-for-laravel/random-cases
language: en
---

[All packages](https://roundly-consulting.com/open-source.md)

[Enums for Laravel](https://roundly-consulting.com/open-source/docs/enums-for-laravel.md)

# Random cases & factories

random() returns a random case — handy for factories, seeders and tests:

```php
NewsCategory::random(); // a random NewsCategory case
```

## In a model factory

```php
namespace Database\Factories;

use App\Enums\NewsCategory;
use App\Models\Article;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends Factory<Article>
 */
final class ArticleFactory extends Factory
{
    /**
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'title' => fake()->sentence(),
            'category' => NewsCategory::random(),
        ];
    }
}
```

## One batch per case

collect() returns every case as a Collection, so seeding a batch per case is a one-liner:

```php
namespace Database\Seeders;

use App\Enums\NewsCategory;
use App\Models\Article;
use Illuminate\Database\Seeder;

final class ArticleSeeder extends Seeder
{
    public function run(): void
    {
        NewsCategory::collect()->each(
            fn (NewsCategory $category) => Article::factory()->count(10)->create(['category' => $category]),
        );
    }
}
```

random() uses PHP’s array\_rand(), which isn’t cryptographically secure — use it for fixtures and demo content, never for anything security-sensitive. On an enum that declares no cases it throws EnumException::noCases() instead of PHP’s ValueError, so it’s caught along with the package’s other errors.

## Show your open-source love

This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.

[More ways to support, including crypto](https://roundly-consulting.com/support-us.md)

By donating, you agree to our [donation terms](https://roundly-consulting.com/donation-terms.md).

[Support our open source work (opens in a new tab)](https://donate.stripe.com/dRmeVe8FX5PF1Qd9pXcEw00) [Join us on Patreon (opens in a new tab)](https://www.patreon.com/cw/roundly)

## Want this built into your product?

We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.

[Get a quote in 48 hours](https://roundly-consulting.com/contact.md) [Browse all packages](https://roundly-consulting.com/open-source/docs/enums-for-laravel.md)
