Framework: $request->replace Method not working as expected

Created on 24 Sep 2017  路  4Comments  路  Source: laravel/framework

  • Laravel Version: 5.5.12 (maybe earlier too)
  • PHP Version: any
  • Database Driver & Version: MySQL 5.6

Description:

When using $request->replace() and subsequently $request->all() the original Data is given back instead of the replaced data.

Steps To Reproduce:

Just create a middleware which will filter out any input with a null value:

public function handle($request, Closure $next)
    {
        $request->replace($this->filterNullValues($request->all()));
        return $next($request);
    }

    public function filterNullValues($dataInput)
    {
        return array_filter($dataInput, function ($element) {
            return $element != null;
        });
    }

Then in the controller you can dd(request()->all()) to see that the data is unchanged.

Presumed source of the problem:

Illuminate\Http\Concerns\InteractsWithInput
Line 188:

public function input($key = null, $default = null)
    {
        return data_get(
            $this->getInputSource()->all() + $this->query->all(), $key, $default
        );
    }

Removing the $this->query-all() solves the issue temporarily.

Most helpful comment

Solution

$this->merge([$param => $new_value]);
$this->query->set($param, $new_value);
$this->request->set($param, $new_value);
if ($this->isJson()) {
    $this->json()->set($param, $new_value);
}

All 4 comments

It was a stupid mistake on my part, an oversight in a test - I was passing in the query string instead of the request body.

  • Laravel 5.2
  • Mysql
  • PHP 7.1

I just ran in the kind of same issue on Laravel 5.2.
I use replace() to sanitize some data. I also tried with merge() but the result is the same.
NOTE: I'm withing the request

$request->get('description') //'test'
$request->replace(['description => 'test2"]);

$request->all(); // description => test2
$request->description //test2
$request->get('description') //test (wrong). 

After investigating the code, doing

$this->request->replace($input); 

Solve the issue.

Is it related ?

Thanks

Solution

$this->merge([$param => $new_value]);
$this->query->set($param, $new_value);
$this->request->set($param, $new_value);
if ($this->isJson()) {
    $this->json()->set($param, $new_value);
}

Thanks to the comment above, I fixed my issue.

I wanted to disable sending query params on Put and Post and this worked pretty good.

    public function handle($request, Closure $next)
    {
        if ($request->getMethod() == 'PUT' || $request->getMethod() == 'POST') {
            $request->query->replace([]);
        }
        return $next($request);
    }
Was this page helpful?
0 / 5 - 0 ratings