How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Retrieve Inputs with a Specific Prefix in Laravel Request
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Learn > Web Development > How to Retrieve Inputs with a Specific Prefix in Laravel Request
Web Development

How to Retrieve Inputs with a Specific Prefix in Laravel Request

how7o
By how7o
Last updated: May 10, 2026
7 Min Read
Laravel request inputs with prefix — filter request()->all() by Str::startsWith
SHARE

Laravel request inputs with prefix comes up whenever a form sends several fields sharing a common key prefix — item_1, item_2, item_3 — and you want to loop over them without listing every key by hand. Laravel doesn’t ship a dedicated helper for prefix matching, but a one-line collect or array_filter on request()->all() does the job. This guide covers the idiomatic patterns, why array-style names (items[]) are usually better when you control the form, and how to validate the filtered keys.

Contents
  • TL;DR
  • When this pattern fits
  • Alternative syntax — request()->only with filtered keys
  • Better shape: array-style names
  • Validating prefixed inputs
  • Writing the rows to the database
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-04-23 on Laravel 11 with PHP 8.3. Originally published 2023-02-08, rewritten and updated 2026-04-23.

TL;DR

Filter request()->all() by key prefix with a collect:

use Illuminate\Support\Str;

$items = collect(request()->all())
    ->filter(fn ($value, $key) => Str::startsWith($key, 'item_'))
    ->all();

foreach ($items as $key => $value) {
    // $key = 'item_1', 'item_2', ...
    // $value = the submitted value
}

When this pattern fits

The typical case is a dynamically-added form where JavaScript appends inputs with incrementing suffixes:

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

PHP parses those into flat top-level keys — item_1, item_2, item_3 — not a nested array. On the server you need a way to find them without hard-coding the count, which is what the filter above does.

Alternative syntax — request()->only with filtered keys

A slightly more explicit form that uses only() for the final picking:

$prefix = 'item_';

$itemKeys = array_filter(
    array_keys(request()->all()),
    fn ($key) => Str::startsWith($key, $prefix)
);

$items = request()->only($itemKeys);

Two passes: first find the keys that start with your prefix, then ask the request for exactly those. Reads well when someone grep-s the codebase for request()->only — they’ll find the call directly — but the collect version is more compact and does the same work in one expression.

laravel request inputs with prefix — collect filter versus array-style items[] form names

Better shape: array-style names

When you control the form, switch to PHP’s native array syntax instead of a suffix-number convention:

<input type="text" name="items[]">
<input type="text" name="items[]">
<input type="text" name="items[]">

PHP parses items[] as a numeric-indexed array, so $request->items returns ['first value', 'second value', 'third value'] natively — no filtering or prefix matching needed. For complex rows, use nested keys:

<input type="text" name="items[0][name]">
<input type="number" name="items[0][quantity]">
<input type="text" name="items[1][name]">
<input type="number" name="items[1][quantity]">

// On the server
foreach ($request->items as $row) {
    // $row['name'], $row['quantity']
}

Reach for the prefix pattern in this guide only when the form isn’t yours to change — an external integration, a third-party script emitting its own names, a legacy page in the app you haven’t refactored yet.

Validating prefixed inputs

For array-style names, wildcards make validation one line:

$request->validate([
    'items.*'          => 'required|string|max:255',
    'items.*.quantity' => 'required|integer|min:1',
]);

For flat prefixed keys (item_1, item_2), Laravel’s validator treats the underscore as a literal character, not a wildcard — so you need to build the rules list dynamically from the filtered keys:

$rules = collect(request()->all())
    ->keys()
    ->filter(fn ($key) => Str::startsWith($key, 'item_'))
    ->mapWithKeys(fn ($key) => [$key => 'required|string|max:255'])
    ->all();

$request->validate($rules);

Another reason to prefer array-style names when you can: the wildcard validation form is much cleaner.

Writing the rows to the database

Once the filtered array is in hand, map it into model rows. Don’t pass the raw $items array into Item::create() — you’d be feeding it keys like item_1 that don’t correspond to any column:

foreach ($items as $key => $value) {
    Item::create([
        'post_id' => $post->id,
        'name'    => $value,
        'sort'    => (int) Str::after($key, 'item_'),
    ]);
}

Str::after($key, 'item_') gives you the numeric suffix ('1', '2', '3') if you need the original position — useful for a stable sort order when the form order matters.

Frequently asked questions

What’s the quickest way to laravel request inputs with prefix?

Build a filtered array with collect and Str::startsWith: collect(request()->all())->filter(fn ($v, $k) => Str::startsWith($k, 'item_'))->all();. You get back only the keys that start with your prefix. Use this in a controller method to split multi-item forms into per-item buckets.

Is request()->only([...]) enough if I don’t know the keys in advance?

No. only() takes a concrete array of keys and returns exactly those. It doesn’t support wildcards or prefixes, so if you don’t know the exact item_1, item_2, item_3 ahead of time, you need to build the key list yourself — typically by filtering request()->all()‘s keys first and then passing the resulting array to only(), or just filtering the values directly.

Should I use array-style names (items[]) instead of prefixed keys?

Yes, when you control the form. PHP parses items[0], items[1], and items[name][] into a native nested array on the server, so $request->items returns the whole collection with no filtering needed. The prefix pattern in this guide is the right answer when you’re integrating with a legacy form, an external POST, or a third-party script you can’t change.

How do I validate prefixed inputs?

Match them with a dot-wildcard in the rule array: ['item_*' => 'required|string|max:255']. Laravel’s validator treats * as a wildcard in array keys and applies the rule to every key matching the pattern. Combine it with sometimes if the field may be absent from some submissions.

Is there a security risk in blindly iterating item_*?

The usual one — mass-assignment. If you pass the filtered array straight into Model::create(), the request can include arbitrary item_X keys that match your model’s $fillable. Scope writes to the columns you intend: Item::create(['name' => $value, 'post_id' => $postId]). And if the prefix keys become row values, trust them the same way you’d trust any user input — validate and cast before storing.

Related guides

  • Laravel Nullable Exists Validation — validating filtered inputs against the database.
  • Laravel Validate Input to Specific Values (in Rule) — allow-list validation on individual fields.
  • Best Way to Insert or Update Records in Laravel Eloquent — persisting the rows you built from the filtered array.
  • How to Call a Controller Method from Another Controller in Laravel — delegating the row-write step to a reusable service.

References

Official Laravel request docs (request()->all, request()->only, validation wildcards): laravel.com/docs/requests. Illuminate\\Support\\Str helpers: laravel.com/docs/strings.

TAGGED:LaravelphpValidation

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Laravel delete file from public folder — File::delete with public_path How to Delete Files from the Public Folder in Laravel
Next Article Laravel DataTables HTML column — rawColumns opt-out of the default escaping How to Add an HTML Column in Laravel DataTables
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Display PHP errors — ini_set + php.ini configuration
How to Display PHP Errors
May 10, 2026
PHP convert string to uppercase — strtoupper and mb_strtoupper
How to Convert a String to Uppercase in PHP
May 10, 2026
PHP string to float conversion with cast, regex cleanup, NumberFormatter
How to Convert a String to Float in PHP
May 10, 2026
PHP merge arrays without duplicates — union operator and array_unique
How to Combine Two Arrays Without Duplicates in PHP
May 10, 2026
PHP delete array element — unset, array_splice, array_filter, array_search
How to Delete an Element from a PHP Array
May 10, 2026

You Might Also Like

Install Composer on Ubuntu — terminal with composer-setup.php and PHP elephant icon
Web Development

How to Install Composer on Ubuntu: Step-by-Step Guide

8 Min Read
Laravel Blade Time Format (HH:MM)
Web Development

How to Show Only Hours and Minutes in Laravel Blade (HH:MM)

3 Min Read
WooCommerce orders as My Account default — menu filter + redirect
Web Development

How to Display Orders Instead of Dashboard on the WooCommerce My Account Page

7 Min Read
Install Laravel on Ubuntu — terminal with composer create-project command and Laravel red-pillar icon
Web Development

How to Install Laravel on Ubuntu: Step-by-Step Guide

9 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?