我有一个简单的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验证?
答案 0 :(得分:0)
我同意elclanrs - 代码看起来不对。
但要回答你的问题 - 你不能这样做吗?
foreach($input as $services)
{
$service = new Service();
$service->userID = $user->id;
$service->services = $services;
if ( ! (is_null($services->services)))
{
$service->save();
}
}