How to retrieve inputs only with specific prefix in Laravel request?

I’m building a form in my Laravel application where users can add multiple items. To keep track of each item, I’ve given each input field a unique name attribute with a common prefix.
For example:

<input type="text" name="item_1">
<input type="text" name="item_2">
<input type="text" name="item_3">

In my controller, I want to retrieve only the inputs whose name attribute starts with “item_”. How can I retrieve inputs with a specific prefix in Laravel? Can anyone help me with this?

Any help would be greatly appreciated! Thank you.

To retrieve inputs with a specific prefix in Laravel, you can use the following code:

$prefix = 'item_';
$inputs = request()->only(array_filter(array_keys(request()->all()), function ($key) use ($prefix) {
    return Str::startsWith($key, $prefix);

foreach ($inputs as $key => $value) {
    // do something

Before using the code, include the following line at the top of your file.

use Illuminate\Support\Str;