0

I have this statement:

$request->lines[$i]['price_ex_vat'] = preg_replace("/([^0-9\\.])/i", "",  $request->lines[$i]['price_ex_vat']);

Its purpose is to remove the currency formatting on a value but I get the error Indirect modification of overloaded property Illuminate\Http\Request::$lines has no effect

Googling tells me I need to use ->merge() but it is just not sinking in how to do that. Any help appreciated.

2 Answers 2

3

As Laravel uses Symfony's ParameterBag to store the request's data it internally does this:

$p = new \Symfony\Component\HttpFoundation\ParameterBag(['foo' => 'bar', 'baz' => 'qux']);
$p->add(['baz' => 'xyz']);

dump(
    $p->all()
);

Which prints out:

array:2 [
  "foo" => "bar"
  "baz" => "xyz"
]

Laravel's request exposes merge method that calls ParameterBag's add method internally. All is good until you manipulate one dimension data.

In your case, the solution could be like this:

$request = \Illuminate\Http\Request::create('/', 'POST', 
    [
        'lines' => [
            ['price_ex_vat' => 'foo'],
            ['price_ex_vat' => 'bar'],
            ['price_ex_vat' => 'baz'],
        ],
    ]
);

$data = $request->input();
$data['lines'][1]['price_ex_vat'] = 'xyz'; // preg_replace or whatever you want.

dd(
    $request->merge($data)->input();
);

Which prints accordingly:

array:1 [
  "lines" => array:3 [
    0 => array:1 [
      "price_ex_vat" => "foo"
    ]
    1 => array:1 [
      "price_ex_vat" => "xyz"
    ]
    2 => array:1 [
      "price_ex_vat" => "baz"
    ]
  ]
]
Sign up to request clarification or add additional context in comments.

Comments

1

I assume $request->lines is an array you are iterating through and want to change price_ex_vat on it. I would suggest making a separate variable to do the changes on it, then use merge to replace $request->lines

$arr = $request->lines;
foreach($arr as $line){ //or you can use a normal for loop if you prefer
 $line['price_ex_vat'] = preg_replace("/([^0-9\\.])/i", "",  $line['price_ex_vat']); //your changes here
}
$request->merge('lines',$arr);

2 Comments

Thanks, I get an error here though Argument 1 passed to Illuminate\Http\Request::merge() must be of the type array, string given
The following worked for me: $lineData = $request->input(); $request->merge($lineData)->input();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.