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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程