gileneusz
gileneusz

Reputation: 1485

Laravel Seeder - how to seed null values on unique column

I've got simple User model:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('email')->unique();
    $table->string('password');
    ...
}

I want to make a seeder that will not fill e-mail adresses that could be filled later by the user:

for($i = 0; $i < 11; $i++){
    $user = new User();
    $user->save();
}

However I've got an obvious error:

SQLSTATE[HY000]: General error: 1364 Field 'email' doesn't have a default value

I tried to use User Model mutator for my seeder:

User Model

public function setEmailAttribute($value) {
    if ( empty($value) ) { // will check for empty string
        $this->attributes['email'] = NULL;
    } else {
        $this->attributes['email'] = $value;
    }
}

User Seeder

for($i = 0; $i < 11; $i++){
    $user = new User();
    $user->setEmailAttribute('');
    $user->app_role = "user";
    $user->save();
}

but this is not working for me here, I'm getting an error again:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'email' cannot be null

However, I don't want to set the email column to unique and nullable permanently, since I want to test this only for my seeder.

Anyone knows how to find a solution here?

Upvotes: 0

Views: 2491

Answers (1)

Kapitan Teemo
Kapitan Teemo

Reputation: 2164

add nullable() to your email column in your migration

    $table->string('email')->unique()->nullable()

then run the following in your command line,

1.composer dump-autoload // updates the changes in your migration

2.php artisan migrate:fresh --seed //new migration and seeds your seeders

Upvotes: 2

Related Questions