Laravel how merge two query result into single object

laravel merge two query builder
laravel merge collections by value
laravel select from multiple tables
laravel merge json
laravel eloquent join 2 tables
laravel join 2 tables using model
laravel join two tables
how to join two collection in laravel

I'm currently stuck on how to merge two query result into single object below is my code.

EDITED

Model methods

public static function getTeamStats($competitionId, $teamId) {
    return TeamCompetitionStatistics::where('competitionId', $competitionId)
        ->where('teamid', $teamId)
        ->where('periodNumber', 0)
        ->get();
}

public static function getTeamPosition($competitionId, $teamId){
    return self::where('latest', 1)
        ->where('competitionId',$competitionId)
        ->where('competitorId', $teamId)
        ->get(['position', 'streak'])
        ->map(function($item, $key){
            $item->position = $item->position . date("S", mktime(0, 0, 0, 0, $item->position, 0));
            if(strpos($item->streak, '-') !== FALSE) {
                $item->streak = str_replace('-', 'L', $item->streak);
            }
            else {
                $item->streak = 'W'.$item->streak;
            }
            return $item;
        });
}

Getting values in controller

$teamStanding = Ladder::getTeamPosition($request->competitionId, $request->id);
$teamStatistics = TeamCompetitionStatistics::getTeamStats($request->competitionId, $request->id);

$result = $teamStatistics->merge($teamStanding);

Returned result: [{'teamstanding': 'data'}, {'teamstatictics': 'data'}]

Expected output: [{'teamstanding': 'data', 'teamstatictics': 'data'}]

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'}]

Laravel how merge two query result into single object , Im currently stuck on how to merge two query result into single object below is my codeEDITEDModel methodspublic static function getTeam Combine two DB query results in Laravel? We can merge easily laravel’s query result with another result object, by using laravel’s Collections method called merge (), It will merge a collection with another collection, and return a single collection containing all the elements in the two objects.

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

Merging two complex Eloquent queries, Next, if you want to merge the results, then you need to get the base collection ( Support\Collection ) first: $connections = $connectionsQuery->get  Merge two array with same keys without loop using PHP. $array1 = [ '0'=> ['name'=>'Jaydeep','Surname'=>'Gondaliya'], '1'=> ['name'=>'Harsukh','Surname'=>'Sojitra'], ]; $array2 = [ '0'=> ['firstname'=>'Hitesh','Lastname'=>'Pandya'], '1'=> ['firstname'=>'Vishal','Lastname'=>'Kakadiya'], ];

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"}]

Combine two DB query results in Laravel?, We can merge easily laravel's query result with another result object, by a single collection containing all the elements in the two objects. Today, We want to share with you Laravel Merge Multiple collections Object And Array.In this post we will show you merge Laravel objects in controller, hear for Laravel 5.7 Collections: Merging Multiple Collection Values we will give you demo and example for implement.In this post, we will learn about Laravel how merge two query result into single object with an example.

Personally I am not a fan on transforming 2 possible big queries in Collections and merge them, seems like a lot of processing in there.

I normally use union(), maybe this can help others. Laravel documentation for unions

$first = DB::table('users')
        ->whereNull('first_name');

$users = DB::table('users')
        ->whereNull('last_name')
        ->union($first)
        ->get();

Combine two query as single laravel, Query 1 $usersdetails = DB::table('users as a') ->join('Appraiser_commands as Laravel how merge two query result into single object , They are used to join  Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems. The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks.

Eloquent: Collections - Laravel, All multi-result sets returned by Eloquent are instances of the The Eloquent collection object extends the Laravel base collection, so it All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays: load loadMissing modelKeys makeVisible makeHidden only toQuery unique  However, the query builder's cursor method returns a LazyCollection instance. This allows you to still only run a single query against the database but also only keep one Eloquent model loaded in memory at a time.

PHP array_merge() Function, Merge two arrays into one array: Note: If you assign only one array to the array_merge() function, and the keys are integers, the function returns a new array  By default, Laravel will use the fully qualified class name to store the type of the related model. For instance, given the one-to-many example above where a Comment may belong to a Post or a Video, the default commentable_type would be either App\Post or App\Video, respectively. However, you may wish to decouple your database from your

How to merge Eloquent Collections, If a trackid is in two collections i want to add the extra total to the existing item, at PHP's array_merge or array_combine (after you have converted the results to Or better still, I'd probably look at running a raw DB query to get the data you  The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

Comments
  • You can use like this: $array = array_merge($teamStanding->toArray(), $teamStatistics->toArray()); return Response::json($array);
  • @PenAndPapers check this laravel.com/docs/5.4/collections#method-merge
  • @PenAndPapers Is it works for you??
  • @HirenGohel it still returns two object in an array
  • it still returns two object in an array
  • I have edited my code, I think you have to use get() function.
  • I've updated my code added methods from my Model, I used your solution but doesnt work
  • Can you use merge($query,$query,...) ?if you have say 3-4 to do ?
  • This is the best answer. it solved what I have been looking for for weeks. Thanks
  • Will merge also work with paginate? For example can we do stuffs like $merged->paginate(10) ??
  • In my project, I am using Fractal for my transformers and I managed to do it there by adding the items in a Fractal Collection $collection = new Collection($items, $transformer, $type); and than add it in the IlluminatePaginatorAdapter from Fractal as $collection->setPaginator(new IlluminatePaginatorAdapter($items)); If you can do it with Fractal, there needs to be a way throught Laravel also.
  • thanks am going to try that. What am trying to achieve is a Facebook type newsfeed where you have multiple models ( posts, videos, status, polls ). Now I want to merge all of them and possibly shuffle them so that each model result is not group. Then finally paginate.
  • This is more on personal preference but from my point of view, this sounds quite costly. What I will do is having a type Post (posts in db) that has default columns but can have relations to video entity, pools entity etc and than its mostly going to be just the correct relations such as hasMany etc. So instead of making a huge query and merge all data together, ill just return a standardised transformer of Posts which includes relations based on the foreign keys that are available. In this way, you will not need to merge any query.
  • Since am paginating per 10 results, I think I might not have to worry about processing time isn't that so? I am new to eloquent relationships on Laravel and my database already contain user generated content so I can't go with that approach right now. Could you show me a code snippet where you used the paginator adapter?? Thanks a lot