1

I have a couple of Laravel migrations.

1-create_countries_table`

Schema::create('countries', function(Blueprint $table)
{
    $table->increments('id');
        $table->string('name');
    $table->timestamps();
});

2-create_cities_table

Schema::create('cities', function(Blueprint $table)
{
    $table->increments('id');
        $table->string('name');
        $table->smallInteger('country_id');
    $table->timestamps();
        $table->foreign('country_id')->references('id')->on('countries');
});

When I use php artisan migrate , I see this error

  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
 (SQL: alter table `cities` add constraint cities_country_id_foreign
 foreign key (`country_id`) references `countries` (`id`))

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

What is the problem?

3 Answers3

1

Try $table->integer('country_id')->unsigned(); instead of $table->smallInteger('country_id');

Pawel Bieszczad
  • 12,925
  • 3
  • 37
  • 40
1

solution for this problem.
add to app/Providers/AppServiceProvider.php

use Illuminate\Support\Facades\Schema;

public function boot(){
    Schema::defaultStringLength(191);
}

https://laravel-news.com/laravel-5-4-key-too-long-error

Rodia
  • 11
  • 3
0

In the laravel when use $table->increments('id'); Laravel create a int(10) field. to connect a field to an id as foregin key it must be int(10). for make a foreign key int 10 we muste use this code:

$table->integer('country_id')->unsigned();

if dont use unsigned(); method, a field will create by int(11) type and isn't mach to int(10)