How can I seed with many to many relations?

Viewed 185

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();
    }
}
1 Answers

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.

Related