Search code examples
phplaraveldotenvphpdotenv

Return datatype from .env in Laravel


I want to have dynamic seeders based on my environment. (eg in testing I want so only seed 100 rows, whereas local it would be 10'000).

I've created seeder.php in the config, which is calling values from the .env file.

When I use the config in my seeder, it's returning a string on a value in the .env that should be an integer. EG:

.env.local:

SEED_USER_COUNT=10000

config\seeder.php:

return [
    'user_count' => env('SEED_USER_COUNT', 10),
];

UserSeeder

factory(User::class, config('user_count'))->create();

The above fails to work and it appears that config('user_count') returns a string "10000" rather than the intger 10000


Solution

  • Cast your variable to int in the configuration file

    config/seeder.php

    return [
        'user_count' => (int)env('SEED_USER_COUNT', 10),
    ];
    

    Call the configuration correctly with the prefix of the file

    UserSeeder

    factory(User::class, config('seeder.user_count'))->create();