我正在处理多步骤注册表单。在第一步骤中,我需要收集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);
}
的问题是其它字段,如address
,city
,state
等是也可填充:
// Customer.php
protected $fillable = ['first_name', 'last_name', 'dob', 'address', 'city', 'state', ...];
我打算收集它们在注册的第二步骤(在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...
}
因此,我的目标是通过在我的验证$rules
变量定义的数组键来过滤$request->all()
字段。这里是我的尝试:
$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'
首先,有没有更有效的/简洁的方式使用array_column
或array_intersect_key
或其他可能无需人工循环办呢?其次,是否还有一种我不知道的更类似Laravel的方法?
有可能是用'只有()'的问题。如果您通过'['first_name','last_name','dob']',并且'$ request'由于某种原因没有'first_name',Laravel会在请求中包含''first_name'=> null'。这可能会引发SQL异常“无默认值”,因为它会尝试插入NULL。 – Alex
是的,但如果您通过'$ request-> input('first_name')'获得输入,您还将获得'NULL'。在这里,你可以定义一个默认值('$ request-> input('first_name','John Doe')')。但我宁愿在模型的'public setFirstNameAttribute($ value)'方法中处理它。 – halloei
解决这个问题的一种方法是在我的'array_keys($ rules)'''array_keys($ request-> all())''上使用'array_intersect'来获得'$ keys'。然后,我调用'Customer :: create($ request-> only($ keys))'这个看起来很安全,但是很好用,并且不明显。你认为还有更好的方法吗? – Alex