How to check if the entity already exists in the bank

1

I'm currently working with models, migrations, seeds and fakers (factory) for testing the database.

So far, I've got to insert 1 admin, whose code I'll introduce:

    DB::table('users')->insert([
        'id'=>'1',

        'name' => 'admin',
        'email' => '[email protected]',
        'password' => bcrypt('admin'),
        'remember_token' => str_random(10),
    ]);

}}

My problem is that when I do the command php artisan db:seed the second time it gives me an error that the users id already has a value of 1 and it is not possible to insert more.

I know that it is possible to check in User models whether an id already exists or not.

What I need is even that in the models of the User verify that there is already 1 admin if it exists it does not insert user but inserts the rest of the migrations.

I leave here the properties of the User model

protected $fillable = [
    'name', 'email', 'password',
];

protected $hidden = [
    'password', 'remember_token',
];
    
asked by anonymous 03.02.2017 / 18:09

2 answers

4

You can also check if the record already exists through Laravel% s own% API.

if (DB::table('users')->where('id', 1)->count() == 0) {

    DB::table('users')->insert([
        'id'=>'1',
        'name' => 'admin',
        'email' => '[email protected]',
        'password' => bcrypt('admin'),
        'remember_token' => str_random(10),
    ]);

}

Basically, what the code does is a direct query to the DB table, under the condition users and count the results. If it is zero, it means that the record does not yet exist, so it executes the id = 1 statement. Otherwise, continue running insert .

    
03.02.2017 / 18:25
2

In your case you can use the firstOrCreate method:

User::firstOrCreate([
    'id'=>'1',
    'name' => 'admin',
    'email' => '[email protected]',
    'password' => bcrypt('admin'),
    'remember_token' => str_random(10),
]);

It will check the database before entering and persisting the User.

    
03.02.2017 / 18:22