如何从请求中的数组中添加/删除元素

Yev*_*yev 3 request laravel laravel-5

我的请求看起来像这样

Array
(
  [name] => Eugene A
  [address] => Array
    (
        [billing] => Array
            (
                [address] => aaa
            )
        [shipping] => Array
            (
                [address] => bbb
            )
    )
)
Run Code Online (Sandbox Code Playgroud)

我需要删除送货地址。但是如何?

我只能删除两个地址,

$request->request->remove('address');
Run Code Online (Sandbox Code Playgroud)

但我不想要。

我只想删除送货地址,就像这样

$request->request->remove('address.shipping');
Run Code Online (Sandbox Code Playgroud)

但这对我不起作用

Laravel 5.6

更新

为什么我需要它?

简单。我已将我的表单请求验证抽象为一个类,该类是Illuminate\Foundation\Http\FormRequest. 我实际上有几个用于验证的类。我在控制器中一一调用它们,如下所示:

app()->make(CustomerPostRequest::class); // validate Customer information
app()->make(AddressSaveRequest::class); // validate Addresses
Run Code Online (Sandbox Code Playgroud)

为什么?

现在我可以在单元测试中模拟这个请求,我可以抽象出我的验证。我可以在很多地方使用地址验证。

但现在我需要更多的灵活性。为什么?

因为 AddressSaveRequest 规则看起来像这样

public function rules(): array
  {
    return [
        'address.*.address'    => [
            'bail',
            'required',
            'string',
        ],
   ...
Run Code Online (Sandbox Code Playgroud)

它验证所有地址。但有时我不想验证送货地址,如果勾选了 chech_box - ship_to_the_same_address。

但是我在单独的文件中抽象了我的地址验证器,它在许多地方使用。有些地方没有显示 ship_to_the_same_address 复选框。

因此我不能使用 'required_unless:ship_to_same_address,yes',

我不能使用

app()->makeWith(AddressSaveRequest::class, ['ship_to_the_same_address ' => 'yes']);
Run Code Online (Sandbox Code Playgroud)

因为泰勒 ...when calling makeWith. In my opinion it should make a new instance each time this method is called because the given parameter array is dynamic.。它确实如此,并且它不能正常工作app()->instance(AddressSaveRequest::class, $addressSaveRequest);并且不能在单元测试中被模拟。

为什么泰勒决定它 - 我真的不知道。

PS 是的,我知道不推荐模拟请求。

lag*_*box 5

如果您尝试从请求本身添加或删除输入:

通过合并数据并让 Laravel 处理正在使用的数据源,您可以很容易地将数据添加到请求中:

$request->merge(['input' => 'value']);
Run Code Online (Sandbox Code Playgroud)

这将合并命名input为请求的输入源的输入。

要删除输入,您可以尝试替换所有输入而没有替换中的特定输入:

$request->replace($request->except('address.shipping'));
Run Code Online (Sandbox Code Playgroud)

只有一个想法可以尝试。