Merge a Laravel Request on the fly
How to change or add a new value to a Laravel request parameter
The solution is in Part B.
Part A: ( Introduction )
Let’s first see how merge() helper function works in Laravel:
merge method merges the given array or collection with the original array or collection. If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection:
$collection = collect(['product_id' => 1, 'price' => 100]);
adding or updating the collection:
$merged = $collection->merge(['price' => 200, 'discount' => false]);
The new collection will be:
// ['product_id' => 1, 'price' => 200, 'discount' => false]
If the given array is not an associative array (the given items’s keys are numeric), the values will be appended to the end of the collection.
$collection = collect(['Desk', 'Chair']);
$merged = $collection->merge(['Bookcase', 'Door']);
// ['Desk', 'Chair', 'Bookcase', 'Door']
B-I: What we are merging is a simple value.
You know that
$request is an object and
$request->all() is an array and is not a collection. Check it yourself: Reference
Now, suppose there is a request that we are going to add or update its value associated to the “image” key. You can simply do this:
B-II: Sometimes the value (parameter) we are merging (updating or adding) is itself an array:
In the case of adding and not updating, just need to follow B-I.
As an example, suppose there is no
'user' key in the
You can simply merge
as an array with the $request
'user' key and its value (that is an array
$arrayOfUserData) is in
$request->all()and we want to modify that array
$arrayOfUserData, first, we have to modify the array somewhere and then merge the modified array with the current request.
I started a new journey and spending my time to dive deeply in Laravel. Stay tuned, follow me and learn daily a small but valuable tip from Laravel without spending much time!