【发布时间】:2021-09-04 20:46:53
【问题描述】:
这是我创建新联系人的功能。
它工作正常,符合预期。
我想知道是否有更好的方法或最佳实践来简化和改进代码。
我只是想提高自己的技能并构建更高效的功能。
public function onSave()
{
$validator = Validator::make(
[
'firstname' => Input::get('firstname'),
'lastname' => Input::get('lastname'),
'phone' => Input::get('phone'),
'email' => Input::get('email'),
'line_1' => Input::get('line_1'),
'line_2' => Input::get('line_2'),
'line_3' => Input::get('line_3'),
'city' => Input::get('city'),
'state' => Input::get('state'),
'postcode' => Input::get('postcode'),
'organisation_id' => Input::get('organisation_id'),
],
[
'firstname' => 'required',
'lastname' => 'required',
'phone' => 'required',
'email' => 'required|email',
'line_1' => 'required',
'line_2' => '',
'line_3' => '',
'city' => 'required',
'state' => 'required',
'postcode' => 'required',
'organisation_id' => 'required',
]
);
if($validator->fails()){
return Redirect::back()->withErrors($validator);
} else {
$contact = new Contact();
$contact->firstname = Input::get('firstname');
$contact->lastname = Input::get('lastname');
$contact->phone = Input::get('phone');
$contact->email = Input::get('email');
$contact->line_1 = Input::get('line_1');
$contact->line_2 = Input::get('line_2');
$contact->line_3 = Input::get('line_3');
$contact->city = Input::get('city');
$contact->state = Input::get('state');
$contact->postcode = Input::get('postcode');
$contact->organisation_id = Input::get('organisation_id');
$contact->save();
//Flash::success('Form Submitted');
return Redirect::to('/contacts/'.$contact->id);
}
}
【问题讨论】:
-
在 Laravel 文档中查找表单请求。这应该是一个好的开始。然后在 Contact 模型上使字段可填充,并使用 $request->only() 方法填充它们
-
如果您的代码有效并且您只是希望有人对其进行审核,请将其发布到Code Review。
-
@MagnusEriksson 感谢您的链接.. 老实说以前不知道))
-
不用担心。跟踪所有不同的 Stack Exchange 站点并不容易 :-)
标签: php laravel octobercms