1

I have this seeder class in my laravel 5.2 app :

class UserTypesTableSeeder extends Seeder
{

    public function run()
{

    DB::table('user_types')->insert([
[
    'type' => 'patient',
    'created_at' => Carbon::now(),
    'updated_at' => Carbon::now(),
],
[
    'type' => 'doctor',
    'created_at' => Carbon::now(),
    'updated_at' => Carbon::now(),
]

]);

    }
}

Now, I want to add another record in the same seeder class. I tried using firstOrCreate() :

UserType::firstOrCreate([
        'type' => 'patient',
        'created_at' => Carbon::now(),
        'updated_at' => Carbon::now(),
    ]);
    UserType::firstOrCreate([
        'type' => 'doctor',
        'created_at' => Carbon::now(),
        'updated_at' => Carbon::now(),
    ]);
    UserType::firstOrCreate([
        'type' => 'admin',
        'created_at' => Carbon::now(),
        'updated_at' => Carbon::now(),
    ]);

but it made duplicate records and so did updateOrCreate().

So, how can I add new records to the same seeder class without duplicating records ??

Rowayda Khayri
  • 489
  • 1
  • 9
  • 21

1 Answers1

4

I think firstOrCreate method is not working as expected because the time of the previous record is not same with the new query. So, if you remove the created_at and updated_at from your query as below:

UserType::firstOrCreate([ 'type' => 'patient' ]);

Now, it should work. Beside, created_at and updated_at will automatically be managed by firstOrCreate method.

Imran
  • 4,582
  • 2
  • 18
  • 37