dimanche 26 juin 2016

Laravel ModelFactory Seeding Pivot Table

I'm using Laravel ModelFactory too seed my database but I'm having problem seeding a pivot table when using model factory

[Symfony\Component\Debug\Exception\FatalThrowableError]

Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, boolean given, called in ............\Cashier\database\seeds\DatabaseSeeder.php on line 27

ModelFactory

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

$factory->define(App\Product::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->unique->randomElement([
            'Item 100',
            'Item 200',
            'Item 300',
            'Item 500',
            'Item 600',
            'Item 700',
            'Item 900',
            'Item 150',
            'Item 250',
            'Item 350',
        ]),
        'price' => $faker->randomFloat(2, 100, 500),
        'image' => $faker->imageUrl(640, 480),
    ];
});

$factory->define(App\Cart::class, function (Faker\Generator $faker) {
    return [
        'quantity' => $faker->numberBetween(1, 10)
    ];
});

DatabaseSeeder

factory(App\Product::class, 10)->create();

factory(App\User::class, 5)->create()->each(function($user)
{
    $user->cart()->save(factory(App\Cart::class)->create()->each(function($cart)
    {
        $cart->products()->attach(App\Product::lists('id')->random());
    }));
});

User Model

public function cart()
{
    return $this->hasOne(Cart::class);
}

Cart Model

public function user()
{
    return $this->belongsTo(User::class);
}

public function products()
{
    return $this->belongsToMany(Product::class);
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/28W5tS4
via IFTTT

Aucun commentaire:

Enregistrer un commentaire