laravel-5laravel-5.8laravel-schema-builder

Laravel 5.8 Schema adding foreign key not working


I'm trying to create foreign keys in Laravel 5.8 and when I migrate my table using Artisan the foreign key not set. In the cities table and provinces table, all id fields are unsigned integers. I'm working with wamp64 on Windows 10.

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->integer('city_id')->unsigned();
        $table->integer('province_id')->unsigned();
        // table Foreign Key
        $table->foreign('city_id')->references('id')->on('cities');
        $table->foreign('province_id')->references('id')->on('provinces');
    });
}

Solution

  • because you have already users rows within your users database table. to achieve that you should make these new fields city_id and province_id as nullable as default value.

    so your migration should be like below :

    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
    
             // I have added here nullable for both city_id and province_id
    
            $table->integer('city_id')->unsigned()->nullable();
            $table->integer('province_id')->unsigned()->nullable();
            // table Foreign Key
            $table->foreign('city_id')->references('id')->on('cities');
            $table->foreign('province_id')->references('id')->on('provinces');
        });
    }