I have a controller where I want to combine data from multiple tables with parallel structures. What I want to end up with in the end is one object I can return from the controller so I can parse it in Backbone.
I want to do something like this:
public function index() { $mc = MainContact::where('verified', '=', '1')->get(); $sm = SendMessage::where('verified', '=', '1')->get(); $obj = (object) array_merge((array) $mc, (array) $sm); return $obj; }
I'm told by another post on StackOverflow that this works in PHP 5.3+. However, this returns the following error in Laravel:
UnexpectedValueException: The Response content must be a string or object implementing __toString(), "object" given.
How do I implement this method in Laravel? Both $mc
and sm
return valid objects in Laravel.
You could simply use array_merge(firstObject,secondObject) function.
Laravel collection merge() method merge any given array to first collection array. If the first collection is indexed array, the second collection will be added to the end of the new collection. The merge() method can accept either an array or a Collection instance.
Merge. $merged = $income1->merge($income2); $income = $merged->all(); So you will be able to use $income to refer both variable!
Approach 1: Convert object into data array and merge them using array_merge() function and convert this merged array back into object of class stdClass. Note: While merging the objects using array_merge(), elements of array in argument1 are overwritten by elements of array in argument2.
Nowadays you can use
$new_collection = $collection->merge($other_collection)
.
This works in Laravel 4 and seems to handle both arrays and collections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With