1

I want to create a "users" table with the email record as a unique value with the Migrations file of my Laravel project

    Schema::create('users', function (Blueprint $table) {
      $table->id();
      $table->string('company')->nullable();
      $table->string('street', 80)->nullable();
      $table->string('zip', 10)->nullable();
      $table->string('city', 80)->nullable();
      $table->string('country', 3)->nullable();
      $table->string('firstname', 80)->nullable();
      $table->string('lastname', 80)->nullable();
      $table->string('email', 80);
      $table->timestamp('email_verified_at')->nullable();
      $table->string('password');
      $table->timestamps();
    });

works fine, but if I replace $table->string('email', 80); with $table->string('email', 80)->unique(); I get the error SQLSTATE[HY000] [2002] Connection refused (SQL: alter table usersadd uniqueusers_email_unique(email))
I read, that adding Schema::defaultStringLength(191); in AppServiceProvider.php would solve this, but even after adding it
and clearing cache with php artisan config:clear && php artisan cache:clear && php artisan view:clear && php artisan route:clear the error is still there.

Friedrich
  • 330
  • 3
  • 10
  • Does this answer your question? [SQLSTATE\[HY000\] \[2002\] Connection refused within Laravel homestead](https://stackoverflow.com/questions/35394230/sqlstatehy000-2002-connection-refused-within-laravel-homestead) – Wahyu Kristianto Feb 28 '22 at 11:32
  • @WahyuKristianto sadly not, the connection gets established and the table is beeing created, the error only occurs when trying to set "email" to unique. I can connect fine to the database – Friedrich Feb 28 '22 at 11:35
  • do you have data in table or its newly created table ? – Aqib Javed Feb 28 '22 at 11:37
  • @AqibJaved it is a newly created table, without any data inside of it – Friedrich Feb 28 '22 at 11:38
  • try after clearing config php artisan config:clear – Aqib Javed Feb 28 '22 at 11:40
  • I cleared config, cache, view and route with `php artisan config:clear && php artisan cache:clear && php artisan view:clear && php artisan route:clear`, didnt change anything, I still get the same error – Friedrich Feb 28 '22 at 11:54

1 Answers1

0

After trying a bit more I realised, that the error was with my mariadb version, as pointed out in this Comment MariaDB 10.4 supports a UNIQUE KEY on a TEXT column, so I changed $table->string('email')->unique() to $table->text('email')->unique() and it worked.

Friedrich
  • 330
  • 3
  • 10