我为现有用户创建了一个新表单。 而且我正在尝试将新值插入数据库,但是这些值不会保存。
public function editUser(Request $request, $id, $check)
{
$curID = $id;
$userData = $request->input();
$curUser = User::Where('id', $curID)->first();
$address = Address::where('id', $userData['address_id']);
------Not working----------------
if(empty($curUser->$address)){
$curUser->insert($address)([
'address_id' => $address->id,
'region_id' => $userData['region'],
'country_id' => $userData['country'],
'city_id' => $userData['city'],
'street_name' => $userData['street_name'],
'house_number' => $userData['house_number'],
'postcode' => $userData['postcode']
]);
-------Not working----------------
} else{
$address->update([
'region_id' => $userData['region'],
'country_id' => $userData['country'],
'city_id' => $userData['city'],
'street_name' => $userData['street_name'],
'house_number' => $userData['house_number'],
'postcode' => $userData['postcode'],
]);
return redirect('client')->with($this->messageBag, "User edited!");
}
答案 0 :(得分:1)
public function editUser(Request $request, $id, $check)
{
$user = User::where('id',$id)->first();
$address = Address::where('id',$request->input('address_id'))->first();
if(empty($address)){
$address=new Address();
}
$address=$this->saveData($address,$request()->all());
$user->update(['address_id'=>$address->id]);
return redirect('client')->with($this->messageBag, "User edited!");
}
protected function saveData(Address $address,array $userData){
$address->region_id= $userData['region'];
$address->country_id= $userData['country'];
$address->city_id= $userData['city'];
$address->street_name= $userData['street_name'];
$address->house_number= $userData['house_number'];
$address->postcode= $userData['postcode'];
$address->save();
return $address;
}