Search code examples
phpmysqllaraveldefaultnullable

Default value for username in SQL database


I'm writing a Laravel application, and for testing in sqlite you need to specify ->nullable() or ->default("123") for all fields in your migration. This confuses me as my User-migration currently looks like this:

public function up() {
    Schema::create('users', function($table) {
        $table->increments('id');
        $table->integer('role_id');
        $table->string('username')->unique();
        $table->string('password');
        $table->string('name');
        $table->string('email');
        $table->integer('max_locations');
        $table->string('auth_token');
        $table->string('remember_token', 100);
        $table->timestamps();
    });
}

Many of these make no sense to add neither ->default("123") nor ->nullable() to. Username is a good example, I can't have null as a username in the database, but if I set a default value that wont work either. The second user that does not have a username that gets added will take the default username, and since usernames have to be unique it will throw an exception.

Currently I have nothing specified, and SQL solves this by giving all these fields the default value "None". Can that be added in some way here? If not, should my username have a default value or should it be nullable?


Solution

  • You can not have NOT NULL column with default NULL value. If you don't want your columns to be nullable, just specify default value like this:

    $table->string('username')->unique()->default('');
    

    In your validation ofcourse you won't let empty values so it is ok.