Home  >  Q&A  >  body text

Ways to avoid errors when adding foreign keys in Laravel

Can you help me? I want to add a foreign key to the posts table that has a reference in the categories table. But when I enter the command php artisan migrate:fresh, it always fails. The error message I got is this PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table 'handconsulting'.'posts' (errno: 150 "Foreignkey constraint is incorrectly formed")" )

This is my postsTable

Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->foreignId('category_id')->constrained('categories')->onDelete('cascade')->onUpdate('cascade');
            $table->string('slug')->unique();
            $table->text('excerpt');
            $table->text('body');
            $table->string('iamge')->nullable();
            $table->timestamp('published_at')->nullable();
            $table->timestamps();
        });

This is my categoriesTable

Schema::create('categories', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->id();
            $table->string('name')->unique();
            $table->string('slug')->unique();
            $table->timestamps();
        });

P粉311617763P粉311617763407 days ago479

reply all(1)I'll reply

  • P粉225961749

    P粉2259617492023-09-09 16:44:04

    this is my approach:

    $table->unsignedBigInteger('category_id');
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade')->onUpdate('cascade');

    reply
    0
  • Cancelreply