check in your database there is already 1 students name table exist, drop that table then re run the migration and let me know what you get?
Apr 29, 2024
3
Level 1
create_students_table migration fails
I have created two tables one for student and another for department. The student table has foreign key department_id:
public function up(): void
{
Schema::create('students', function (Blueprint $table) {
$table->id('student_id');
$table->string('name');
$table->string('email');
$table->string('contact',11);
$table->unsignedBigInteger('department_id');
$table->foreign('department_id')->references('department_id')->on('departments');
$table->timestamps();
});
}
department table is as follows:
public function up(): void
{
Schema::create('departments', function (Blueprint $table) {
$table->id('department_id');
$table->string('name',255);
$table->timestamps();
});
}
Running migration gives error :
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'students' already exists (Connection: mysql, SQL: create table `students` (`student_id` bigint unsigned not null auto_increment primary key, `name` varchar(255) not null, `email` varchar(255) not null, `contact` varchar(11) not null, `department_id` bigint unsigned not null, `created_at` timestamp null, `updated_at` timestamp null)
Level 1
Thanks for the replies . I tried deleting the students table but even after that it showed the same error. Tried commands php artisan migrate:fresh and refresh . The solution i got was changing the order of migration .The order which gave error was student and then department , so i just changed the date of department to less than student and it worked.
Most times the reason for this error is usually due to the order of which the migration files are listed or error due to type casting.
Always make sure that the migration of the file which the foreign constraints is to be imposed on comes after the parent migration. And for the latter, make sure its an unsignedBigInteger , although former version of laravel (<5.4) could ignore this type casting error. by Oluwatimilehin Odubola.
Please or to participate in this conversation.