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:
- 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 ], ]); }
- 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 ], ]);