I'm trying to insert into two tables that are related through a many to many relationship, but I need the user id to pass to the related table, how do I get it?
This are the store and getCountry function:
public function store(Request $request)
{
ini_set('max_execution_time', 300);
$users = $request->all();
try
{
DB::beginTransaction();
foreach ($users as $user)
{
$dbUser = $this->getUser($user['USERNAME']);
Log::error($dbUser);
$dbUser->name = $user['NOMBRE'];
$dbUser->user_name = $user['USERNAME'];
$dbUser->email = $user['CORREO'];
$dbUser->last_name = $user['APELLIDO'];
$dbUser->password = $user['PASSWORD'];
$this->isSet('TIPO-USUARIO', $user);
$user_type_id = $this->getUserId($user['TIPO-USUARIO']);
$dbUser->user_type_id = $user_type_id->id;
foreach (explode(',', str_replace(' ', '', $user['PAIS-USUARIO'])) as $c)
{
$country = $this->getCountry($c);
$dbUser->countries()->save($country);
}
$dbUser->save();
}
DB::commit();
}
catch (Exception $e)
{
DB::rollBack();
throw new HttpException(500, 'My error message');
}
}
private function getCountry($id)
{
$country_id = Country::where('id', $id)->first();
return $country_id;
}
The error i get right now is:
SQLSTATE[23000]: Integrity constraint violation:
1048 Column 'user_id' cannot be null (SQL: insert into
user_country(country_id,user_id) values (1, ?))
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire