This error is generated by the seed "You requested 1 items but there are only 0 items in the collection"

2

I'm trying to make a seed with Laravel 5.1 and the problem is that it generates the data from the users table, but from the other 2 it does not. My codes are as follows.

ModelFactory

$factory->define(Blog\User::class, function (Faker\Generator $faker) {
return [
    'name' => $faker->name,
    'email' => $faker->safeEmail,
    'password' => bcrypt(str_random(10)),
    'tipoUsuario' => $faker->randomElement(['Administrador','Moderador','Invitado']),
    'remember_token' => str_random(10),
];
});

$factory->define(Blog\Articulo::class, function (Faker\Generator $faker) {
    return [
        'titulo' => 'Probando el seeder y slug',
        'contenido' => $faker->paragraph,
         'foto' => 'http://programacion.net/files/article/20151030111039_laravel-logo-white.png',
         'etiqueta' => 'Laravel, Curso, Blog, Primero, 2016',
        'user_id' => \Blog\User::all()->random()->id,
        'categoria_id' => \Blog\Categoria::all()->random()->id,
    ];
});

$factory->define(Blog\Categoria::class, function (Faker\Generator $faker) {
    return [
    '    nombre' => $faker->randomElement(['Html5','Html4.1','CSS','Laravel-5','Laravel-4','JavaScript']),
    ];
});

And this is my DatabaseSeeder from here I call you.

public function run()
{
    Model::unguard();

    //factory('Blog\User',50)->create();
    factory('Blog\Articulo',20)->create();
    factory('Blog\Categoria',5)->create();
    // $this->call(UserTableSeeder::class);

    Model::reguard();
}

When I run the "php artisan db: seed" or "php artisan migrate --seed" It generates that error You requested 1 items but there are only 0 items in the collection

    
asked by Luis Morales 23.09.2016 в 05:45
source

1 answer

1

In the articles factory you are getting a random ID of Category that apparently does not exist yet, taking into account that the seeder of categories is executed later:

    // ...
    'categoria_id' => \Blog\Categoria::all()->random()->id,
    // ...

It would be solved by changing the order of execution of the category and article seeders:

public function run()
{
    Model::unguard();

    factory('Blog\User',50)->create();
    factory('Blog\Categoria',5)->create();
    factory('Blog\Articulo',20)->create();
    // $this->call(UserTableSeeder::class);

    Model::reguard();
}
    
answered by 23.09.2016 / 06:18
source