Laravel – SQLSTATE[42000]: Syntax error or access violation

I am trying to make a migration in my Laravel project, but i get the following error:

SQLSTATE[42000]: Syntax error or access violation: 1072 Key column ‘department_id’ doesn’t exist in table (SQL: alter table courses add index courses_department_id_index(department_id))

I removed 1 line from my table.php file which i thought caused the error, and then it worked just fine. Could someone explain where my syntax is wrong in the following line?

$table->foreign('department_id')->references('id')->on('departments')->onDelete('cascade');

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The error means that there is no department_id column that references the foreign key, Because you should create column before creating a foreign key, I think your migration file should contains the following:

$table->unsignedBigInteger('department_id');
$table->foreign('department_id')->references('id')->on('departments')->onDelete('cascade');


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x