Jakub Kohout
Jakub Kohout

Reputation: 1944

Laravel seeding with relationship Eloquent\Builder failing

I'm trying to seed my database with like this:

factory(App\User::class, 1)
    ->create()
    ->each(function($u) {
        $role = factory(App\Role::class)->create();
        $u->role()->save( $role );
    });

and these are my model factories:

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => 'Jakub Kohout',
        'email' => '[email protected]',
        'password' => bcrypt('Uchiha'),
        'role_id' => 1
    ];
});

$factory->define(App\Role::class, function (Faker\Generator $faker) {
    return [
        'role_name' => 'Admin',
    ];
});

But I got this error:

Undefined property: Illuminate\Database\Eloquent\Builder::$orders

What am I doing wrong?

Upvotes: 3

Views: 704

Answers (1)

Moritur
Moritur

Reputation: 1758

Sadly, the each function does not work with single elements. You have to create more than one Model to use the each function:

factory(App\User::class, 2)->create()->each(function($u) {
    $role = factory(App\Role::class)->create();

    $u->role()->save( $role );
});

Source

When only one element is created, the instance is returned directly instead of a collection.

This should work for your case:

$user = factory(App\User::class)->create();

$role = factory(App\Role::class)->create();

$user->role()->save( $role );

Upvotes: 4

Related Questions