Ad

How To Get The Common Values From 2 Laravel Collections

I have 2 Collections in Laravel, and I want only common values in my $result object. I see that $collection->intersect() works only for 1D array. Below are the collections

Collection {#1086 ▼
  #items: array:5 [▼
    0 => {#1115 ▼
      +"name": "Light"
      +"class": "ABC"
      +"id": 4
    }
    1 => {#1113 ▼
      +"name": "Milo"
      +"class": "XYZ"
      +"id": 10
    }
    2 => {#1120 ▼
      +"name": "Milo Test"
      +"class": "ABC"
      +"id": 12
    }
    3 => {#1102 ▼
      +"name": "KMSMiloCow"
      +"class": "ABC"
      +"id": 16
    }
    4 => {#1106 ▼
      +"name": "MiloCows"
      +"class": "XYZ"
      +"id": 18
    }
  ]
}

Collection {#1086 ▼
      #items: array:5 [▼
        0 => {#1115 ▼
          +"name": "Light"
          +"class_name": "ABC"
          +"id": 4
        }           
      ]
    }

Now in my result, I just need this

Collection {#1086 ▼
          #items: array:5 [▼
            0 => {#1115 ▼
              +"name": "Light"
              +"class": "ABC"
              +"id": 4
            }           
          ]
        }
Ad

Answer

I think using collection method each and contains, it can be done like this

    $collection1->each(function ($value, $key) use ($collection2){
        return $collection2->contains($value);
    });
    dd($collection1);

I test it in routes file web.php like

use Illuminate\Support\Collection;
Route::get('test', function(){
    $collection1 = new Collection([
        'bear',
        'whale',
        'chicken',
        'tardigrade'
    ], [[
        'bear8',
        'whale44',
        'chicken45',
        'tardigrade445'
    ]]);
    $collection2 = new Collection([
        'bear1',
        'whale2',
        'chicken3',
        'tardigrade4'
    ], [[
        'bear',
        'whale',
        'chicken',
        'tardigrade'
    ]]);
    $collection1->each(function ($value, $key) use ($collection2){
        return $collection2->contains($value);
    });
    dd($collection1);
});
Ad
source: stackoverflow.com
Ad