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([

Nice and easy :)

More Posts

Laravel Queue Delays Not Working

Using Laravel 5.7 queues along with Redis I found that whilst the events were being dispatched and handled by the...

Notifications delayed on Android Pie?

Just recently I noticed that notifications for WhatsApp and Facebook Messenger were not coming through. They'd only show if I...