【发布时间】:2015-10-18 08:16:38
【问题描述】:
我在 laravel 中有一个有效的 crud 代码,但我的问题是验证。这是我的代码:
public function update(Request $request)
{
$room_id = $this->route('route');
$validator = \Validator::make(\Request::all(), [
'roomNumber' => 'required|unique:rooms,roomNumber,',
'type' => 'required',
'price' => 'required',
]);
if(!$validator -> fails()){
$id = \Request::input('id');
$com = Room::find($id);
$room -> roomNumber = \Request::input('roomNumber', 'Test');
$room -> type = \Request::input('type', 'Test');
$room -> price = \Request::input('price', '0.00');
$room -> description = \Request::input('description', 'Test');
$com -> save();
return redirect('rooms') -> with('message', 'Room Updated!');
} else {
return redirect('rooms') -> withErrors($validator->errors());
}
}
如您所见,roomNumber 是必需的,并且应该是唯一的。我的问题是,这是更新代码。如果我只想更新price 或type 之类的字段怎么办?每当我更新一个字段时,我总是会在我的视图中看到 The room number has already been taken.,因为是的,roomNumber 在我的验证中应该是唯一的。
如何更新仍会检查 room number 是否唯一的特定字段,但如果我正在更新的数据位于同一字段中,它只会更新其他字段,例如 type 和 @987654327 @?如果我的问题含糊不清,请纠正我。谢谢!
例子:
我的房间表中有 2 个数据
Data 1:
roomNumber: 214
type: Queen
price: 150.00
Data 2:
roomNumber: 619
type: Suite
price: 250.00
现在如果我将Data 1 字段price 从150.00 更新为160.00,我将收到验证错误The room number has already been taken.,因为它也会在我更新时验证roomNumber。如果我要更新的数据相同,如何在不验证 roomNumber 的情况下更新它?
【问题讨论】:
-
抱歉,当您说“..但如果我要更新的数据在同一个字段中,它只会更新其他字段,例如类型和价格”,您能否再澄清一下。能举个例子吗?
-
@codegeek 更新了我的帖子