Rara
Rara

Reputation: 23

How can I seed with many to many relations?

I have a restaurant application where I created seeders for My restaurants(users) and for the types of cuisine(types). Since these two tables have a relation many to many I have a pivot table named type_user.

But this table doesn't get seeded when I run the seeders. How can I seed the pivot table type_user in my UserSeeder with id's from the user table and type table?

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\User;
use App\Type;

class UsersSeeder extends Seeder
{
/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    $users = config('restaurants');

    foreach ($users as $user) {
        $new = new User();

        $new->name = $user['name'];
        $new->slug = Str::slug($user['name'], '-');
        $new->email = $user['email'];
        $new->password = Hash::make($user['password']);
        $new->address = $user['address'];
        $new->vat_number = $user['vat_number'];

        $new->types()->attach($user->id);

        if (array_key_exists('thumb', $user)) {
            $new->thumb = $user['thumb'];
        } else {
            $new->thumb = 'users_thumbs/food_placeholder.jpg';
        }
        $new->save();
    }
}

Upvotes: 1

Views: 523

Answers (2)

Tuychiev Toir
Tuychiev Toir

Reputation: 380

It is used for laravel latest versions (~8.5)

I am used to call has method (User::factory()->has()) it allows you to generate without any data but you should create factory for your model. For example:

Migration:

Schema::create('roles', function (Blueprint $table) {
    $table->id();
    $table->string('role');
    $table->timestamps();
});

Schema::create('role_user', function (Blueprint $table) {
    $table->id();
    $table->foreignIdFor(\App\Models\User::class);
    $table->foreignIdFor(\App\Models\Role::class);
    $table->timestamps();
});

User Model:

class User extends Authenticatable
{
    use HasFactory;

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}

Seeder:

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        User::factory(10)
            //->for(Profile::factory(), 'profile')
            ->has(Role::factory(2), 'roles');
    }
}

has method for many relationship. for method for single relationship.

Upvotes: 0

Navneeta
Navneeta

Reputation: 58

Try attach after save and you need to have type_id which you want to attach with user

$user = $new->save();

$user->type()->attach($type_id)

Also make sure you have setup the relationship in models.

Upvotes: 0

Related Questions