Search code examples
phplaravelcollectionsfiltering

Get first qualifying result while searching for qualifying items in a 4-dimensional Laravel collection


I created this Laravel collection:

$headquarters = collect([
    [
        'headquarter' => 'Leon',
        'offers' => [
            ['name' => 'Name1', 'slug' => 'Name1'],
            ['name' => 'Name2', 'slug' => 'Name2']
        ]
    ],
    [
        'headquarter' => 'Granada',
        'offers' => [
            ['name' => 'Name3', 'slug' => 'Name3'],
            ['name' => 'Name4', 'slug' => 'Name4'],
            ['name' => 'Name5', 'slug' => 'Name5']
        ]
    ]
]);

I want to filter this collection by headquarter and offers slug in order to get a single offer.

Right now, I am trying using filter.

 $offer = $this->headquarters()
     ->filter(function($hq) use ($headquarter, $slug) {
         return $hq['headquarter'] == $headquarter && $hq['offers']['slug'] == $slug;
     });

But with no success.


Solution

  • You can get all offers in specific headquarter with this code

    $this->headquarters()->where('headquarter', 'Leon')[0]['offers'][0];
    

    Then for each all offers

    foreach ($this->headquarters()->where('headquarter', 'Leon')[0]['offers'] as $offer) {
                print_r($offer);
            }
    

    or try this code

        $offer = collect($this->headquarters()->where('headquarter', $headquarter)
                                ->first()['offers'])
                        ->where('slug', $slug)->first();