I have the following models:
TourCategory.php [hasMany('App\Tour', 'category_id');]
And code snippet which does the following tasks:
Find tour category by it's slug.
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
dd($tours->count());
in the above mentioned method When there is only one tour in DB saved without region it returns 1
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 ?
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();