skip to Main Content

I’m trying to create a simple table with a foreign key referencing the default “users” table of Laravel.

Migration ran successfully, but when I see the newly created table in PHPMyAdmin, it doesn’t show the foreign key.

Here is my simple migration file:

Schema::create('larachat_chat_rooms', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedBigInteger('creator_id')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();
        $table->softDeletes();
    });

enter image description here

3

Answers


  1. From phpmyadmin go to the specific table => Operations tab => Table options => change Storage Engine to innoDB save and return to your table you will see the relation view

    Login or Signup to reply.
  2. Can you try this and run php artisan migrate

    Schema::create('larachat_chat_rooms', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedBigInteger('creator_id');
            $table->softDeletes();
            $table->timestamps();
    
    
            $table->foreign('creator_id')->references('id')->on('users')->onDelete('cascade');
        });
    

    and let me know if it works fine for you. what I think about this is, you need to create the column first, then you can specify it to be foreignkey. Refer doc

    Login or Signup to reply.
  3. I noticed Eloquent seams not to build constraint whenever you create the field and set foreign at the same sentence. Like bellow:

    $table->unsignedBigInteger('creator_id')
        ->foreign('creator_id')->references('id')
            ->on('users')->onDelete('cascade');
    

    instead, you should do like

    $table->unsignedBigInteger('creator_id');
    
    $table->foreign('country_id')->references('id')->on('users')->onDelete('cascade');
    

    I am not a database specialist but I use dbeaver and mysql workbench and both deal differently whenever I apply those changes to migration scripts for they build and show relations in diagram only when I code like the second sample.

    Can anyone confirm this, or even elaborate why? Please 🙂 ! Thanks.

    PS: Laravel 9.3.1

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search