0

After trying all of this possibility, still, have this error message:

 SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'categories' 
 (SQL: alter table `users` add constraint `users_category_id_foreign` foreign key 
 (`category_id`) references `categories` (`id`) on delete cascade)

The code of relation in users migration:

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

The image of the table:

Image

Help :(

Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
  • You modified your users migration to add the category in the original users migration right? It fails because the Categories table does not exists yet, and you are referencing it. – nakov Nov 22 '19 at 15:29

1 Answers1

0

Remove those lines from the create_users_table migration and add this to the create_categories_table.

// function up() below the Schema::create('categories'..

Schema::table('users', function (Blueprint $table) { 
    $table->unsignedBigInteger('category_id')->nullable();
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});

I made it nullable because again, you are adding it to an existing table, so if you happen to have any users in the table, the migration will fail again if there is no default value.

nakov
  • 13,938
  • 12
  • 60
  • 110
  • What! why are you making like this ( it's working btw :) ) but can you pls explain why my way is showing the error! –  Nov 22 '19 at 15:52
  • I said above. Because when you create the users table, you are referencing a table that does not exists yet. Because the `create_categories` table migration runs after that. So you need to create the categories table first in order for the reference to work. – nakov Nov 22 '19 at 15:54