How to merge Laravel objects in controller

Tags: ,



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.

Answer

What you can do here is merge the arrays of the two query result and then use the Response with json output like shown below.

$array = array_merge($mc->toArray(), $sm->toArray());
return Response::json($array);


Source: stackoverflow