Laravel how merge two query results into a single object Laravel how merge two query results into a single object laravel laravel

Laravel how merge two query results into a single object


You can use all() function.

$teamStanding = Ladder::getTeamPosition($request->competitionId, $request->id)->get();$teamStatistics = TeamCompetitionStatistics::getTeamStats($request->competitionId, $request->id)->get();$merged = $teamStatistics->merge($teamStanding);$result = $merged->all();// return [{'teamstanding': 'data', 'teamstatictics': 'data'}]


Try merge()

The merge method merges the given array or collection with the original collection.

$first = ModelName::where('<fieldName>','<searchText>')        ->get();$second = Album::where('<fieldName>','<searchText>')    ->get();$finalResult = $first->merge($second);$finalResult->each(function($record){    echo $record-><fieldName>.'<br />';});


Adding my answer as the above solutions didn't quite work for me, both just added two separate objects to one array: {"Name":"A Name"},{"Surname":"A Surname"}. I had to collect my array and use first.

https://laravel.com/docs/5.4/collections#method-merge

$first  = $modelone->where('Id', '1')->first(['Name']);$second = $modeltwo->where('Thing', '1')->first(['Surname']);    $collection = collect($first);    $merged     = $collection->merge($second);    $result[]   = $merged->all();    return $result;//output: [{"Name":"A Name","Surname":"A Surname"}]