Home > front end >  Laravel how to use $request except on nested array
Laravel how to use $request except on nested array

Time:07-06

Is it possible to use $request->except on a nested array? This is the request data:

    [▼
      "id" => 1
      "products" => array:1 [▼
        0 => array:4 [▼
          "id" => 1
          "name" => "sample product"
          "date" => "07/04/2022"
          "frequency" => array:1 [ …1]
        ]
      ]
    ]

My goal is to remove some key value pairs e.g. removing id, date and frequency. My desired result would be:

    [▼
      "id" => 1
      "products" => array:1 [▼
        0 => array:1 [▼
          "name" => "sample product"
        ]
      ]
    ]

What I've tried so far is to use Arr:except function:

$request->products = Arr::except($request->products['0'], ['id', 'date', 'frequency']);

But this should be applied on all items. Let's say I have two item products, the desired result would be:

        [▼
          "id" => 1
          "products" => array:2 [▼
            0 => array:1 [▼
              "name" => "sample product"
            ]
            1 => array:1 [▼
              "name" => "sample product 2"
            ]
          ]
        ]

Need your inputs on what's the best approach for this. Thank you!

CodePudding user response:

Unless I am missing something obvious, could you not just iterate over the products in your $request object?

$filtered = [];

foreach ($request->products as $product) {
    $filtered[] = Arr::except($product, ['id', 'date', 'frequency']);
}

dd($filtered);

Resulting in $filtered containing:

^ array:2 [▼
  "id" => 1
  "products" => array:2 [▼
    0 => array:1 [▼
      "name" => "sample product"
    ]
    1 => array:1 [▼
      "name" => "sample product 2"
    ]
  ]
]

Update 1

I can see that the $request except only works on the top level

Not sure what you mean by this as the above principle works for me.

$filtered = [];
foreach ($request->products as $product) {
    $filtered[] = Arr::except($product, ['id', 'date', 'frequency']);
}
$request->merge(['products' => $filtered]);

If I supply the above with the following:

{
    "id": 1,
    "products": [
        {
            "id": 1,
            "name": "sample product",
            "date": "07/04/2022",
            "frequency": []
        },
        {
            "id": 2,
            "name": "sample product 2",
            "date": "07/04/2022",
            "frequency": []
        }
    ]
}

Then do a dd($request->products); I get:

^ array:2 [▼
  0 => array:1 [▼
    "name" => "sample product"
  ]
  1 => array:1 [▼
    "name" => "sample product 2"
  ]
]
  • Related