laravel-5

Why am I getting an error that rand is not recognized when seeding in laravel


I am trying to run php artisan:migrate --seed for my DatabaseSeeder.php but I keep getting this error in my terminal:

InvalidArgumentException : Unknown formatter "rand"

239|                 return $this->formatters[$formatter];
240|             }
241|         }

242| throw new \InvalidArgumentException(sprintf('Unknown formatter "%s"', $formatter)); 243| } 244| 245| /** 246| * Replaces tokens ('{{ tokenName }}') with the result from the token method call

Here is the code from my Database Seeder php

    <?php
use App\Question;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
        factory(App\User::class, 3)->create()->each(function($u){
            $u->questions()
              ->saveMany(
                  factory(App\Question::class, rand(1,5))->make()
            );
        });
    }
}

Why am I getting this error?


Solution

  • It may be better to store rand() outside the factory closures. Try to change your code to:

    public function run()
    {
        $number = rand(1,5);
        factory(App\User::class, 3)->create()->each(function($u) use ($number){
            $u->questions()
              ->saveMany(
                  factory(App\Question::class, $number)->make()
            );
        });
    }