-1

I have two results sets $result1 and $result2 which are returning below results. $result1 contains 1 record and $result2 has 2 records. How can i append $result2 into $result1 at index[1] without hardcoding index? $result1 may have many records so i just want to append at the end.

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 10
                    [organisation] => Tyre Manufacturer
                    [creaedtme] => 2022-01-06 02:55:15
                )

        )

)
Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 7
                    [organisation] => A2Z PEST CONTROL
                    [firstprefix] => Ms
                    [creaedtme] => 2022-01-07 07:40:23
                )

            [1] => stdClass Object
                (
                    [id] => 11
                    [organisation] => Spare Parts
            [creaedtme] => 2022-01-06 03:00:06
                )


        )

)

Below is my source code i tried but its not working

$own_leads = DB::table('leaddata')->where('createdy', $user_id)->orderBy('id','DESC')->get();
// Initialize employee leads
$employee_leads = (object)[];

// If logged in user is State Level Admin then get all leads of that state
if ($user_role == 'State Level Admin') {
    $employee_leads = DB::table('users')
        ->join('leaddata', 'users.id', '=', 'leaddata.createdy')
        ->whereIn('users.stateid', $user_state)
        ->get();
}
echo $count = $own_leads->count();
$merged = $own_leads->concat($employee_leads);
$merged->all();
echo "<pre>";
print_r($own_leads);
echo "</pre>";
Neeraj
  • 8,625
  • 18
  • 60
  • 89
  • https://laravel.com/docs/8.x/collections#method-merge – aynber Jan 10 '22 at 13:46
  • @aynber the merge method is not merging second result set into first one. can you please suggest on this? – Neeraj Jan 10 '22 at 13:51
  • How are you using it? If you do `$merged = $result1->merge($result2)`, then $merged should have all 3 records. $result1 and $result2 are left untouched. – aynber Jan 10 '22 at 13:54
  • @aynber i had overlooked at your response. But that worked for me. Can you please update your answer as Solution below, i will accept it – Neeraj Jan 10 '22 at 13:55

1 Answers1

2

Both merge and concat return a new collection without overwriting the old one. By doing

$merged = $result1->merge($result2);

or in the case of the code you added,

$merged = $own_leads->concat($employee_leads);

$merged will contain the new collection, while the original two collections remain the same.

aynber
  • 22,380
  • 8
  • 50
  • 63