Skip to content
Advertisement

SQLSTATE[HY000]: General error: 1364 Field ‘country_id’ doesn’t have a default value

I have two countries and states tables between them hasMany belongsTo relation.

I want to fill table states using seeder but it gives me this error:

'country_id' doesn't have a default value

StatesTableSeeder.php

public function run()
    {
     $now = Carbon::now()->toDateTimeString(); 
     State::insert([ 
       ['name' =>'tihit','slug' =>'tihit','created_at'=> $now,'updated_at' =>$now],
    ])->countries()->attach(1); 
    }

Advertisement

Answer

You never defined a country in which you want to add a state. There are two ways of doing this:

  1. Loop through all countries and then create a state for each of them

Get all the countries first:

$countries = Country::get(); //Assuming your model name is Country
$now = Carbon::now()->toDateTimeString();

Loop them:

foreach ($countries as $country){
        State::insert([
            [
                'country_id' => $country->id,
                'name' =>'tihit',
                'slug' =>'tihit',
                'created_at'=> $now,
                'updated_at' =>$now
            ],
        ]);
    }
  1. Add a state to a single (specific) country:

First find a specific country:

$country = Country::findOrFail($id); //Or use any other filter to find a single country
$now = Carbon::now()->toDateTimeString();

Then add a state to that country

State::insert([
            [
                'country_id' => $country->id,
                'name' =>'tihit',
                'slug' =>'tihit',
                'created_at'=> $now,
                'updated_at' =>$now
            ],
        ]);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement