1

I just started working with Laravel and i'm trying to seed my DB. I have a many to many relationship between the users and shops table.

enter image description here

When i'm running php artisan DB:seed the seeder for shops isn't running. And if i run php artisan db:seed --class=ShopsTableSeeder i'm getting an Error SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value

The factory file :

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Models\Shop;

$factory->define(Shop::class, function () {
    $faker = Faker\Factory::create('fr_FR');

    return [
        'title' => $faker->text($maxNbChars = 20),
        'description' => $faker->text(250),
        ...
        'phone' => $faker->phoneNumber,
        'active_until' => $faker->dateTimeBetween('+0 days', '+2 years'),
    ];
});

And the seeding file :

<?php

namespace Database\Seeders;

use App\Models\Shop;
use App\Models\User;
use Illuminate\Database\Seeder;

class ShopsTableSeeder extends Seeder
{

    public function run()
    {
        factory(Shop::class, 10)->create();

        foreach (Shop::all() as $shop){
            $users = User::inRandomOrder()->take(rand(1,3))->pluck('id');
            $shop->users()->attach($users);
        }
    }
}

how can i set the column user_id in the factory to connect a shop to user ?

Abdo Rabah
  • 1,670
  • 2
  • 15
  • 31

0 Answers0