How to avoid or make sure that entries in the table are unique while seeding a laravel table

83 views Asked by At

I am building a lead management system using laravel10 and I had several tables like lead,individualLead,BusinessLead,Statuses,sources,etc The statuses table can have values like Cancelled,Pending,Followup started, Completed etc. While seeding the database the same values are feeded as multiple entries to the table ,how to make sure that the table only has unique and relevant data while seeding the database. I am also building the Api's for these ta[[[enter image description here](https://i.stack.imgur.com/Wjh5R.png)](https://i.stack.imgur.com/IgA37.png)](https://i.stack.imgur.com/LLUYQ.png)bles too

I had tried to add unique() constrain, as well as looping while seeding the table

2

There are 2 answers

0
Rohit On
  1. Use faker to generate unique values:

    'contact_no' => $this->faker->unique()->phoneNumber,

    'email' => $this->faker->unique()->safeEmail,

  2. In migration table:

     $table->unique(['email']);
     $table->unique(['phoneNumber']);
    
0
B L Praveen On

If you are running seeder first time. It will create. In case running again without db:fresh than will update the record.

you can add all the unique composite keys in the first parameter of updateOrCreate function

 \App\User::updateOrCreate(['user_email','phone'],$data);

Indexing the table column while migration will not allow to create duplicate records.