我有一个简单的 foreach 循环,它检查每个选定的服务(来自 html 表单),然后通过 Laravel 4 模型将该信息保存到数据库中。信息保存得很好,但即使它为空,它也会保存 foreach 输入。如果选择了数据,我该如何保存?
控制器
public function getServices() {
$user = User::find(Auth::user()->id);
$input = [
'rooms' => Input::get('rooms'),
'pr_deodorizer' => Input::get('pr_deodorizer'),
'pr_protectant' => Input::get('pr_protectant'),
'pr_sanitizer' => Input::get('pr_sanitizer'),
'fr_couch' => Input::get('fr_couch'),
'fr_chair' => Input::get('fr_chair'),
'pr_sectional' => Input::get('pr_sectional'),
'pr_ottoman' => Input::get('pr_ottoman'),
'pr_tile' => Input::get('pr_tile'),
'pr_hardwood' => Input::get('pr_hardwood')
];
$empty = '<i class="icon-warning-sign"></i> No services were selected. Need help? Contact us';
if(empty($input['rooms']) && empty($input['pr_deodorizer']) &&
empty($input['pr_sanitizer']) && empty($input['pr_protectant'])
&& empty($input['fr_couch']) && empty($input['fr_chair'])
&& empty($input['pr_sectional']) && empty($input['pr_ottoman'])
&& empty($input['pr_tile']) && empty($input['pr_hardwood'])
){
return Redirect::to('book/services')->withErrors($empty)->withInput();
}
foreach($input as $services)
{
$service = new Service();
$service->userID = $user->id;
$service->services = $services;
$service->save();
}
return Redirect::to('book/schedule');
}
这就是它保存到我的数据库中的方式:
id userID services price created_at updated_at
171 1 3 NULL 2013-09-17 03:13:24 2013-09-17 03:13:24
172 1 NULL 2013-09-17 03:13:24 2013-09-17 03:13:24
173 1 NULL 2013-09-17 03:13:25 2013-09-17 03:13:25
174 1 NULL 2013-09-17 03:13:25 2013-09-17 03:13:25
175 1 NULL 2013-09-17 03:13:25 2013-09-17 03:13:25
176 1 NULL 2013-09-17 03:13:25 2013-09-17 03:13:25
177 1 NULL 2013-09-17 03:13:25 2013-09-17 03:13:25
178 1 NULL 2013-09-17 03:13:25 2013-09-17 03:13:25
179 1 NULL 2013-09-17 03:13:25 2013-09-17 03:13:25
180 1 NULL 2013-09-17 03:13:25 2013-09-17 03:13:25
服务栏是我正在看的。用户选择了一个 serviceID 为 3 但没有别的服务。但它占用了空行,这会导致报告错误。我怎样才能让它只保存他们实际填充的数据?Laravel 4 验证是否可行?