insert "dummy" record into foreach loop
Hey everyone. I have an array that lists every subcategory within a main category. There is a condition that each subcategory must have a business within the subcategory, and that business must be active. Now, in my blade, I iterate through my array and list each subcategory name with an anchor tag to link each subcategory to its respective page.
That being said - I want some of my categories to have a "dummy" subcategory that isnt a real subcategory, but links to another main category. For example, I have a main category called "Home Services" and another main category called "Cleaning Services". I want a "dummy" subcategory within "Home Services" called "Cleaning Services" that links to the main category "Cleaning Services". I have this set up already and its working, but the code is messy and I know there is a better way to do this. Im going to want to do this for more than one main category.
CategoryController.php
public function index($category_id)
{
$data['category'] = Category::with('children')->where('slug',$category_id)->first();
if($data['category']->id == 25){
$data['subcategories'] = $data['subcategories']->where(function($query){
$query->whereHas('businesses', function($query) {
$query->where('status', 1);
})
->orWhere('id', 485); // this is my dummy "Cleaning Services" object that I had to create to make this work
})
->orderBy('name')
->get()
->toArray();
} else {
$data['subcategories'] = $data['subcategories']
->whereHas('businesses', function($query) {
$query->where('status', 1);
})
->orderBy('name')
->get()
->toArray();
}
category.blade.php
@foreach($subcategories as $subcategory)
<li>
// Intercept "Cleaning Services" and redirect to main category
@if($subcategory['name'] == "Cleaning Services")
<a href="{{URL::route('services::category_id', ['category_id' => 'cleaning-services']) }}"> {{ $subcategory['name'] }}</a>
@else
<a href="{{URL::route('services::subcategory_id', ['category_id' => $category['slug'], 'subcategory_id' => $subcategory['slug']]) }}"> {{$subcategory['name']}}</a>
@endif
</li>
@endforeach
To make this work, I have to actually ADD a subcategory called "Cleaning Services" within my "Home Services" model. I'm sure there is a way to just manually insert a $subcategory['name'] into my array (and resort the array by $subcategory['name'] ), all within my foreach loop in my blade. I'm just lost. Can anyone give any suggestions?
Please or to participate in this conversation.