0

Below are my migrations

Migrations

The users table have a relation with the customer table

In user:

$table->integer('customer_id')->unsigned();
$table->foreign('customer_id')->references('id')->on('customers');

When i call php artisan migrate:refresh --seed, artisan given me the following error:

[Illuminate\Database\QueryException]                                         
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL  
  : alter table `users` add constraint `users_customer_id_foreign` foreign ke  
  y (`customer_id`) references `customers` (`id`))                             



  [PDOException]                                                          
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

Because the customers table does not exists... (obvious)

Is there a way to solve this problem? I know changing the date of the files will fix this but there should be a beter approach

yooouuri
  • 2,578
  • 10
  • 32
  • 54
  • Rename the `customers` table migration file so that it appears before `users` table migration file. Now drop database and run your command. – Mahbub Feb 20 '17 at 09:02

3 Answers3

2

You have to create the table you're referencing to before adding the foreign key. A solution would be to remove the foreign key constraint from your user table migration and create a new migration which adds the foreign key constraints.

3472948
  • 801
  • 4
  • 15
0

Try to make it separately.

public function up()
{
    Schema::create('users', function(Blueprint $table) {
        $table->increments('id');
        $table->integer('costumer_id')->unsigned();
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

   Schema::table('users', function($table) {
       $table->foreign('costumer_id')->references('id')->on('costumers');
   });
}

Another thing you can try(since laravel 5.3):

unsignedInteger('column_name') instead of ('column_name')-unsigned()
Maarten Peels
  • 1,002
  • 1
  • 13
  • 29
0

If you had set one field as "Unsigned" and other one not. Once you should set both columns to Unsigned it works.