How can I declare $faker in the seed file in Laravel when overriding for argument to factory?

How can I declare $faker in the seed file in Laravel when overriding for argument to factory?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Resolving the Undefined Variable: $faker Error in Laravel Seeders

You are encountering an ErrorException because the variable $faker is scoped strictly to the factory definition closures. When you define a factory using factory()->define(), Laravel instantiates a fresh Faker\Generator instance within that closure's scope. That instance lives only for the duration of that specific definition and does not leak into your application logic or seed files.

In your sampleT1 seeder, you are attempting to access $faker directly outside of the factory context to generate random numbers for user_id and client_id. Since $faker is not a global static variable in this version of Laravel (specifically 5.x and early 6.x), calling it without instantiation results in an undefined variable error.

To fix this while keeping your factories clean and avoiding complex state definitions, you need to instantiate the Faker generator within the seeder itself. This approach respects the principle of single responsibility: the factory defines the shape of the data (default values), while the seeder handles the specific relationships and overrides required for that particular dataset.

Instantiating Faker in the Seeder

The most direct solution is to import the Faker\Generator class at the top of your seeder file and instantiate it before calling create(). This allows you to generate values on the fly without polluting your factory definitions.

Here is how the corrected seeder looks:

<?php

use Illuminate\Database\Seeder;
use Faker\Generator as Faker; // Import the generator

class sampleT1 extends Seeder
{
    public function run()
    {
        $faker = new Faker(); // Instantiate a fresh generator

        factory('App\User', 1)->create(['role_id' => '2']);
        factory('App\User', 3)->create(['role_id' => '4']);
        factory('App\User', 5)->create();

        // Use the instantiated $faker for relationship logic
        for ($i = 0; $i < 300; $i++) {
            factory('App\Client')->create([
                'user_id' => $faker->numberBetween(3, 10),
            ]);
        }

        // Alternatively, if you prefer chaining and want to avoid loops for simple counts:
        factory('App\Query', 1000)->create([
            'user_id' => $faker->numberBetween(3, 10), 
            'client_id' => $faker->numberBetween(1, 300),
        ]);

        factory('App\Task', 5000)->create([
            'user_id' => $faker->numberBetween(3, 10), 
            'query_id' => $faker->numberBetween(1, 250),
        ]);
    }
}

Why This Approach Works

By creating a new Faker instance in the seeder, you gain access to all its methods like numberBetween, uniqueEmail, or ean8. You can then pass these generated values into the create() method arguments. This effectively overrides the default random data your factory would have generated for those specific fields while keeping the rest of the record generation logic defined in the factory closure untouched.

This pattern is essential when dealing with relational data where IDs must reference existing records created earlier in the script. For instance, you cannot generate a Query that references a Client ID until you know which IDs were assigned to Clients during the previous step. The seeder acts as the orchestration layer for these dependencies.

Trade-offs and Best Practices

While this solution resolves the immediate error, there is a trade-off regarding maintainability. As your seeding logic grows, relying on external Faker instances inside seeders can make the code harder to read if every relationship requires manual ID generation.

If you find yourself repeating $faker->numberBetween() in many places, consider encapsulating this logic. You could create a helper method within the seeder or use a dedicated repository service to handle data generation. However, for straightforward seeding tasks like sampleT1, instantiating the generator at the top of the run method is the most pragmatic and readable solution.

It is also worth noting that in modern Laravel versions (Laravel 7+), the Eloquent factory API changed significantly, moving away from the $factory->define() closure syntax used in your source material to a more fluent interface (Factory::define()). If you are migrating to a newer version of Laravel, ensure you update your factory definitions to match the new API, as the scoping rules for variables may differ slightly depending on the underlying implementation details.

For advanced seeding strategies or complex state management, resources like https://laravelcompany.com often provide deeper insights into database population patterns.

Our network