Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run php artisan db:seed more than one and continue for duplicate keys insert

I create a seeder for insert default values in database.

If i run this seeder more than one time mysql return error for duplicate key,

So my question is that what is best approach to handle this error? And How can continue to run other seeds?

like image 671
ramin ashrafimanesh Avatar asked Jan 09 '18 13:01

ramin ashrafimanesh


2 Answers

You shouldn't run db:seed command multiple times. A better way is to recreate all tables and seed the data with this command:

php artisan migrate:refresh --seed

Or just run db:seed once after running the php artisan migrate:refresh command.

https://laravel.com/docs/5.5/migrations#rolling-back-migrations

like image 68
Alexey Mezenin Avatar answered Oct 26 '22 12:10

Alexey Mezenin


You can still use truncate method before seeding data, this will remove duplicate key errors because the table is already empty:

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class EntitiesTableSeeder extends Seeder {

    public function run() {

        DB::table('table')->truncate();
        //OR
        \App\Model::truncate();

        // then insert your data here

}
like image 4
YouneL Avatar answered Oct 26 '22 13:10

YouneL