2017-01-11 28 views
0

我正在处理多步骤注册表单。在第一步骤中,我需要收集first_namelast_name,和dob,然后创建Customer对象只有那些三个字段如何通过验证规则中的密钥过滤请求数据?

// RegistrationController.php 
public function store_profile(Request $request) { 
    $rules = ['first_name' => '...', 'last_name' => '...', 'dob' => '...']; 
    $this->validate($request, $rules); 

    Customer::create($request); 
} 

的问题是其它字段,如addresscitystate等是也可填充

// 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_columnarray_intersect_key或其他可能无需人工循环办呢?其次,是否还有一种我不知道的更类似Laravel的方法?

回答

6

only()(和except())呢?

Customer::create($request->only(['first_name', 'last_name', 'dob']));

Customer::create($request->only(array_keys($rules)));

编辑:在Laravel 5.5,有another solution

$rules = ['first_name' => '...', 'last_name' => '...', 'dob' => '...']; 
$data = $this->validate($request, $rules); 

Customer::create($data); // $data contains only first_name, last_name and dob 
+0

有可能是用'只有()'的问题。如果您通过'['first_name','last_name','dob']',并且'$ request'由于某种原因没有'first_name',Laravel会在请求中包含''first_name'=> null'。这可能会引发SQL异常“无默认值”,因为它会尝试插入NULL。 – Alex

+0

是的,但如果您通过'$ request-> input('first_name')'获得输入,您还将获得'NULL'。在这里,你可以定义一个默认值('$ request-> input('first_name','John Doe')')。但我宁愿在模型的'public setFirstNameAttribute($ value)'方法中处理它。 – halloei

+0

解决这个问题的一种方法是在我的'array_keys($ rules)'''array_keys($ request-> all())''上使用'array_intersect'来获得'$ keys'。然后,我调用'Customer :: create($ request-> only($ keys))'这个看起来很安全,但是很好用,并且不明显。你认为还有更好的方法吗? – Alex

0

我会做这样的,如果我是你:

​​

或更简单:

Customer::create($request->only(['first_name', 'last_name', 'dob']));