Merge a Laravel Request on the fly

How to change or add a new value to a Laravel request parameter

Panjeh
3 min readJan 14, 2021

The solution is in Part B.

Part A: ( Introduction )

Let’s first see how merge() helper function works in Laravel:

The 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:

$merged->all();

// ['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']);

$merged->all();

// ['Desk', 'Chair', 'Bookcase', 'Door']

Before you continue with the rest of this tutorial, I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.

https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs

Part B:

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

https://panjeh.medium.com/check-variable-is-a-laravel-collection-4757c005463d

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:

$fileName = “IMAGE_1”

B-II: Sometimes the value (parameter) we are merging (updating or adding) is itself an array:

B-II-adding:

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 $request->all()

You can simply merge $arrayOfUserData

as an array with the $request

B-II-updating:

If '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.

Result:

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!

--

--