PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, March 5, 2022

[FIXED] Laravel QueryException when adding unique constraint

 March 05, 2022     laravel, laravel-7, php     No comments   

Issue

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.


Solution

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.



Answered By - Friedrich
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing