Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge Laravel objects in controller

Tags:

php

laravel

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.

like image 311
sehummel Avatar asked Jan 11 '13 17:01

sehummel


People also ask

How do I combine two objects in laravel?

You could simply use array_merge(firstObject,secondObject) function.

How do I merge two laravel collections?

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.

How do I merge variables in laravel?

Merge. $merged = $income1->merge($income2); $income = $merged->all(); So you will be able to use $income to refer both variable!

What is the best method to merge two PHP objects?

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.


1 Answers

Nowadays you can use

$new_collection = $collection->merge($other_collection).

This works in Laravel 4 and seems to handle both arrays and collections.

like image 118
trm42 Avatar answered Oct 03 '22 00:10

trm42