DEV Community

Vincent Tommi
Vincent Tommi

Posted on

Understanding the PostgreSQL Error: `SQLSTATE[42P01]`

When I ran php artisan migrate:fresh, Laravel failed while creating the menu_categories table.

The error was:

SQLSTATE[42P01]: Undefined table:
ERROR: relation "kitchen_sections" does not exist
Enter fullscreen mode Exit fullscreen mode

What does this error mean?

PostgreSQL uses the word relation to refer to database objects such as tables. In this case, PostgreSQL could not find the kitchen_sections table that my migration referenced.

My menu_categories migration contained:

$table->foreignId('kitchen_section_id')
    ->nullable()
    ->constrained('kitchen_sections')
    ->nullOnDelete();
Enter fullscreen mode Exit fullscreen mode

This code tells Laravel to:

  1. Create a kitchen_section_id foreign-key column.
  2. Reference the id column in the kitchen_sections table.
  3. Allow the foreign key to be NULL.
  4. Set kitchen_section_id to NULL if its referenced kitchen section is deleted.

The relationship itself was valid. The problem was that Laravel attempted to create it before the referenced table existed.

Why did Laravel run the migration in the wrong order?

My migration files were initially named:

2026_09_18_034452_create_menu_categories_table.php
2026_09_22_040308_create_kitchen_sections_table.php
Enter fullscreen mode Exit fullscreen mode

Laravel executes migrations in timestamp order. Since the menu_categories migration had an earlier timestamp, it ran first.

However, menu_categories depended on kitchen_sections, creating a dependency conflict.

How I fixed it

I renamed the kitchen-sections migration so that it would run before the menu-categories migration:

2026_09_18_030000_create_kitchen_sections_table.php
2026_09_18_034452_create_menu_categories_table.php
Enter fullscreen mode Exit fullscreen mode

I also removed an empty, unused migration file that was named recreate_menu_categories_table.

After correcting the migration order, I ran:

php artisan migrate:fresh
Enter fullscreen mode Exit fullscreen mode

The migrations completed successfully.

The main lesson

A foreign key requires its referenced table and column to exist before the constraint can be created. In Laravel, migration timestamps determine the execution order, so dependent tables must be created first.

When troubleshooting SQLSTATE[42P01], check whether the referenced table exists, whether its migration has run, and whether the migration files are ordered correctly.

Top comments (0)