Zoul's avatar
Level 5

1005 Can't create table `db`.`reports` (errno: 150 "Foreign key constraint is incorrectly formed

Hi team,

All other tables having same data type, i just created reports and category_reports table, however i can't migrate them to db, i changed data type, but stil not working.

  SQLSTATE[HY000]: General error: 1005 Can't create table `db`.`reports` (errno: 150 "Foreign key constraint is incorrectly formed") (Connection: mysql, SQL: alter table `reports` add constraint `reports_category_report_id_foreign` foreign key (`category_report_id`) references `category_reports` (`id`))

reports table

        Schema::create('reports', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id')->unsigned();
            $table->unsignedBigInteger('category_report_id')->unsigned();
            $table->timestamps();
            $table->softDeletes();  

            $table->foreign('category_report_id')->references('id')->on('category_reports')-		 
               >onCascade('delete');
            $table->foreign('user_id')->references('id')->on('users')->onCascade('delete');
        });

in category_repots table

 Schema::create('category_reports', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->longText('title');
            $table->timestamps();
        });

in users table

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id')->unsigned();
            $table->rememberToken();
            $table->timestamps();

        });

All other tables i have having $table->bigIncrements('id'); as id

and then $table->unsignedBigInteger('x_id')->unsigned(); as foreign key

I appreciate your support !

0 likes
9 replies
webard's avatar

$table->bigIncrements('id') is unsigned by default, so there is no need to use ->unsigned() on it.

From Laravel 5.8, $table->id() is BIGINT by default, so just write $table->id()

You definition looks okey but it's messy, and error comes from incosistency betweeen id field in category_reports and category_report_id in reports table. Please check that both columns has same type, length and UNSIGNED flag.

What comes to mind is that you used an unsigned method on a field that is already unsigned:

 $table->unsignedBigInteger('category_report_id')->unsigned();

which reversed its operation.

Zoul's avatar
Level 5

Thanks a lot for your help @webard , i will refactor all my code and implement the newer way what Tray2 suggested and see

Tray2's avatar
Tray2
Best Answer
Level 74

You really should use the newer syntax.

 Schema::create('reports', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(User::class)
				->constrained()
				->onDelete('cascade');
            $table->foreignIdFor(CategoryReports::class)
				->constrained()
				->onDelete('cascade');
            $table->timestamps();
            $table->softDeletes();  

        });

You are using longText for the title, and that is 4GB, use string which is 255 bytes, and if you need more use text which is 64KB.

 Schema::create('category_reports', function (Blueprint $table) {
            $table->id();
            //$table->longText('title'); 
			$table->string('title'); 
            $table->timestamps();
        });

As for the users table you should use the one provided by laravel.

Make sure to run the category_reports migration first or it will fail.

Zoul's avatar
Level 5

@Tray2 Many thanks for your help, also for catching longText, i though i needed it for store title in 3 different languages, but i would stay with text since this should be enough.

The way you suggested is more organised and having less code as well. I see that we don't have to mention anymore the id ( category_report_id) which is needed to be called in my Report model like

 public function category()
     {
         return $this->belongsTo(CategoryReport::class,'category_report_id');
     }

My question is which id i can call on this method ?

Tray2's avatar

@Zoul You don't have to pass any second parameter, it is only necessary if you cal the foreign key something else than category_report_id which you don't when you use the

 $table->foreignIdFor(CategoryReports::class)
				->constrained()
				->onDelete('cascade');
1 like
Zoul's avatar
Level 5

@Tray2 thank you so much for your support. I did refactor my code and i guess it passed for the above tables, however i have another :

 Cannot declare class App\Models\CreateGalleriesPhotosTable, because the name is already in use

  at database\migrations21_06_11_090235_create_galleries__photos_table.php:7
      3▕ use Illuminate\Database\Migrations\Migration;
      4▕ use Illuminate\Database\Schema\Blueprint;
      5▕ use Illuminate\Support\Facades\Schema;
      6▕
  ➜   7▕ class CreateGalleriesPhotosTable extends Migration
      8▕ {
      9▕     /**
     10▕      * Run the migrations.
     11▕      *


   Whoops\Exception\ErrorException 

  Cannot declare class App\Models\CreateGalleriesPhotosTable, because the name is already in use

  at database\migrations21_06_11_090235_create_galleries__photos_table.php:7
      3▕ use Illuminate\Database\Migrations\Migration;
      4▕ use Illuminate\Database\Schema\Blueprint;
      5▕ use Illuminate\Support\Facades\Schema;
      6▕
  ➜   7▕ class CreateGalleriesPhotosTable extends Migration
      8▕ {
      9▕     /**
     10▕      * Run the migrations.
     11▕      *

  1   vendor\filp\whoops\src\Whoops\Run.php:510
      Whoops\Run::handleError("Cannot declare class App\Models\CreateGalleriesPhotosTable, because the name is already in use", "D:\xampp\htdocs\db\code\oaahdv1\database\migrations21_06_11_090235_create_galleries__photos_table.php")

  2   [internal]:0
      Whoops\Run::handleShutdown()

I cleared cached and tried to remove this table CreateGalleriesPhotosTable completely but i have again another error with other table

in CreateGalleriesPhotosTable table

class CreateGalleriesPhotosTable extends Migration  
{
    /**
     * Run the migrations.
     *
     * @return void 
     */
    public function up()
    {
        Schema::create('galleries_photos', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(Gallery::class)->constrained()->onDelete('cascade');
            $table->string('photo')->nullable();
            $table->boolean('status')->default(false);
            $table->timestamps();
        });
    }

in galleries table


class CreateGalleriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('galleries', function (Blueprint $table) {
            $table->id();
            $table->text('title')->nullable();
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

Any idea what is going wrong pls ?

Tray2's avatar

@Zoul it seems that you have a model with the same name as your migration class, or you managed to copy it to you models namespace.

1 like
Zoul's avatar
Level 5

@Tray2 thats could be the reason, but as i don't see any dublicate or mistmatch names its so hard to debug, will check deeper i might see the error

Zoul's avatar
Level 5

Will open a new threads thanks both for your help

Please or to participate in this conversation.