How to remove values from request in Laravel

As the title says, this one is how to remove values from the request object in Laravel.

A lot of the answers on StackOverflow don't work anymore. You can't use $request->remove('your_item');. Instead you have a few options:

  • offsetUnset()
  • replace() with except().

I feel like the Laravel API is often under utilised. I for one didn't know of its existance for quite some time. It's really useful for finding out which methods are available. You can check out the offsetUnset method on the Laravel API docs.

Working Example:

The offsetUnset() is probably the easiest and quickest way to remove a singluar value from the request. $request->offsetUnset('thing_to_remove'); If however you need a bit more freedom to, such as removing multiple values or persisting the request into your model, then you can use the replace() and except() methods.

$request->replace( $request->except('thing_to_remove') );

You can even pass in an array to the except method to remove multiple things: $request->replace( $request->except(['thing_to_remove', 'another_thing']) );

What this does is replace everything in your request object with everything, apart from the value(s) you specifiy.

Also when peristing to the database:

$post = Post::create($request->except([
    'thing_to_remove',
    'another_thing_to_remove'
]));

Nice and easy :)

More Posts