doutuobao4004 2017-01-11 16:30
浏览 24
已采纳

如何通过验证规则中的键过滤请求数据?

I am working on a multi-step registration form. In the first step, I need to collect first_name, last_name, and dob, then create a Customer object with only those three fields:

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

    Customer::create($request);
}

The problem is that other fields, such as address, city, state, etc. are also fillable:

// Customer.php
protected $fillable = ['first_name', 'last_name', 'dob', 'address', 'city', 'state', ...];

I intend to collect them in the second step of the registration (in public function store_address()), yet nothing will prevent the user from POSTing those additional fields to step one:

// 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...
}

Hence, my goal is to filter $request->all() fields by the array keys defined in my validation $rules variable. Here's my attempt:

$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'

First, is there a more efficient/concise way to do it using array_column or array_intersect_key or other, possibly without manual looping? Second, is there a more Laravel-like approach that I am not aware of?

  • 写回答

2条回答 默认 最新

  • douhuan6157 2017-01-11 16:34
    关注

    What about only() (and except())?

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

    or

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

    Edit: In Laravel 5.5, there's 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题