Search code examples
phplaravellaravel-5.7

Check if values in collection has null value or not


I have the following models:

  1. Tour.php [belongsTo('App\Region'),belongsTo('App\TourCategory')]
  2. Region.php [hasMany('App\Tour');]
  3. TourCategory.php [hasMany('App\Tour', 'category_id');]

    And code snippet which does the following tasks:

  4. Find tour category by it's slug.

  5. Get tours having that particular category.
  6. Get all unique region names from those tours.

      public function fetchByCategory($slug)
      {
       $category = TourCategory::where('slug','=', $slug)->first();
       $tours = $category->tours()->with('region')->get(['region_id']);
       $regions = $tours->pluck('region')->unique();
    
       return view('frontend.pages.travel-style')
       ->withResults($regions)
       ->withCategory($category);
      }
    

But some of my created tour doesn't have region. A null value is set by default when a tour is stored without a region.

This is causing my app to break down as I'm printing my data's in view in the following way:

@foreach($results as $region)
    <div class="uk-width-1-2@s">
        <a href="{{ route('region2package',[$category->slug,$region->slug]) }}">
         <div class="uk-height-medium uk-flex uk-flex-center uk-flex-middle uk-background-cover uk-light" data-src="{{ asset($region->thumb) }}" uk-img>
        </a>
            <h3><a href="{{ route('region2package',[$category->slug,$region->slug]) }}">{{ $region->name }}</a></h3>
        </div>
    </div>
@endforeach
  1. When I do dump and die dd($tours->count()); in the above mentioned method When there is only one tour in DB saved without region it returns 1
  2. When I do dd($regions); it gives this:

    Collection {#570 ▼
     #items: array:1 [▼
     0 => null
      ]
     }
    

I would be very thankful if anyone could suggest the best possible way to check the items in collection contains null value or not ?


Solution

  • Instead of finding null value from collection you can filter your collection so null value automatically removed from your collection.

    $regions = $tours->pluck('region')->unique()->filter();