Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Insert Seed if data doesn't already exist

Is there any way to run a laravel seed to only insert the records if they do not exist already?

My current laravel seeder looks like this

DB::table('users')->insert([
                //Global Admin
                [
                    'member_id' => 11111111,
                    'firstname' => 'Joe',
                    'lastname' => 'Bloggs'
                ], 
                [
                    'member_id' => 22222222,
                    'firstname' => 'Jim',
                    'lastname' => 'Bloggs'
                ], 

            ]);

Pretty standard!

would I have to wrap each and every insert in a try catch? like this

try {
   DB::table('users')->insert(['member_id' => 11111111, 'firstname' => 'Joe', 'lastname' => 'Bloggs']);
} catch(Exception $e){
  //Die silently
}
try {
   DB::table('users')->insert(['member_id' => 22222222, 'firstname' => 'Jim', 'lastname' => 'Bloggs']);
} catch(Exception $e){
  //Die silently
}

Later on I might want to add extra rows to the same seeder without having to write a new one, and re run php artisan db:seed to only add my new rows.

Is this possible?

like image 359
S_R Avatar asked Sep 06 '25 16:09

S_R


2 Answers

You can achieve this by Eloquent firstOrCreate.

The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the attributes from the first parameter, along with those in the optional second parameter.

So, if you identify the user by member_id, you can do something like this:

    User::firstOrCreate(
        ['member_id' => 11111111],
        [
            'firstname' => 'anakin',
            'lastname' => 'skywalker',
            'password' => Hash::make('4nak1n')
        ]
    );

If you want to locate the record by 'member_id', 'firstname' and 'lastname' fields, something like this:

    User::firstOrCreate(
        [
            'member_id' => 11111111,
            'firstname' => 'anakin',
            'lastname' => 'skywalker'
        ],
        [
            'password' => Hash::make('4nak1n'),
        ]
    );
like image 136
porloscerros Ψ Avatar answered Sep 08 '25 12:09

porloscerros Ψ


Seeding is only supposed to be used for testing, anyways.

Why don't you just execute php artisan migrate:fresh --seed?

This will refresh your database (deletes the tables) then runs all your migrations again and finally seeds the database again.

You should never be using seeders in production.

Just add the new data to your seeder, run migrate:fresh and re-seed :)

like image 31
stokoe0990 Avatar answered Sep 08 '25 10:09

stokoe0990