zhuocr zhuocr - 3 years ago 188
PHP Question

How to remove query part from $request->all() in Laravel framework?

In my project, I use

$request->all()
to get params.

But
$request->all()
includes query thing. When I post a
name => 1
to my API
'domain.com/api/users'


var_dump $request->all()


example :

[
'api/users' => null,
'name' => 1,
]


I want to remove like
'api/users'
in my every
$request->all()
. What should I do?

Answer Source

While I cannot guarantee that I perfectly understood the question but based on my understanding, to filter out fields that are not sent as part of the request, then using request()->only(['field', 'field_2']) should be sufficient given the instance stated in L5.5 upgrade notice about request->only method:

enter image description here

It means given the example I have, if field_2 is not present in the request, then it is discarded.

If you are on Laravel BEFORE 5.5 then $request->all() will give you only existing field, else for L5.5 you use request->only() You can give it a try and see how they work.

ON Laravel <= 5.4 and also L5.5

Finally, if you still get those fields as null then you can simply use array_filter($request_array) e.g:

    $request_only = $request->all();
    $requests_without_null_fields =  array_filter($request_only);

This will remove all fields that are null preserving only fields that are not null.

Hope this is useful.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download