Ale*_*lex 1 php validation laravel laravel-5.3
我正在制作一个多步骤的注册表格.在第一步中,我需要收集first_name,last_name和dob,然后创建一个Customer对象,只有这三个领域:
// RegistrationController.php
public function store_profile(Request $request) {
$rules = ['first_name' => '...', 'last_name' => '...', 'dob' => '...'];
$this->validate($request, $rules);
Customer::create($request);
}
Run Code Online (Sandbox Code Playgroud)
的问题是,其他领域,例如address,city,state等是也可填充的:
// Customer.php
protected $fillable = ['first_name', 'last_name', 'dob', 'address', 'city', 'state', ...];
Run Code Online (Sandbox Code Playgroud)
我打算在注册的第二步(in public function store_address())中收集它们,但没有什么能阻止用户将POST这些附加字段添加到第一步:
// RegistrationController.php
public function store_profile(Request $request) {
$rules = ['first_name' => '...', 'last_name' => '...', 'dob' => '...'];
$this->validate($request, $rules); // won't validate 'address', 'city', 'state'
Customer::create($request); // will store everything that's fillable,
// no matter if it was validated or not...
}
Run Code Online (Sandbox Code Playgroud)
因此,我的目标是$request->all()通过验证$rules变量中定义的数组键过滤字段.这是我的尝试:
$data = [];
foreach(array_keys($rules) as $key) {
$val = $request->{$key};
if (! empty($val))
$data[$key] = $val;
}
// in the end, $data will only contain the keys from $rules
// i.e. 'first_name', 'last_name', 'dob'
Run Code Online (Sandbox Code Playgroud)
首先,有没有更有效的/简洁的方式,用做array_column或array_intersect_key或其他可能无需人工循环?第二,是否有更多类似Laravel的方法,我不知道?
怎么样only()(和except())?
Customer::create($request->only(['first_name', 'last_name', 'dob']));
要么
Customer::create($request->only(array_keys($rules)));
编辑:在Laravel 5.5中,有另一种解决方案:
$rules = ['first_name' => '...', 'last_name' => '...', 'dob' => '...'];
$data = $this->validate($request, $rules);
Customer::create($data); // $data contains only first_name, last_name and dob
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2961 次 |
| 最近记录: |