How to check if the entity already exists in the bank

Asked

Viewed 3,113 times

1

I am currently working with models, Migrations, Seeds and fakers (Factory) for database testing.

So far I’m ordering to insert 1 admin, whose code I present:

    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 command php artisan db:seed the second time it gives me an error that the id of users already has value of 1 and it is not possible to insert more.

I know it is possible to check in User models if there is already an id equal or not.

What I need is even that in the User models check if 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',
];

2 answers

4


You can also check if the record already exists through the API itself DB of Laravel.

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 table users, on condition id = 1 and counts the results. If it is zero, it means that the record does not yet exist, then executes the statement insert. Otherwise, keep running the seeders.

  • Thanks Anderson Carlos Woss worked perfectly

2

In your case you can use the method firstOrCreate:

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

It will check in the bank before inserting and persisting the User.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.