php - Laravel - How to identify which model (out of two) via single html select option
Get the solution ↓↓↓I am listing Categories and Subcategories to the user in a select. If a category has subcategories, parent category is disabled to get selected. There are cases where category doesn't have any subcategories. So categories and subcategories are listed in same select.
On my controller side, I have two models (Category and Subcategory). how could i determine the selection? (whether it's category or subcategory)
Answer
Solution:
You can handle this few different ways.
For example give subcategories a value withsub_category_
prefix and check in the controller if selected values has stringsub_category_
in it like following.
<option disabled>{{ $element->title }}</option>
@foreach($element->subcategories as $subcategory)
<option value ="sub_category_{{$subcategory->id}}">- {{ $subcategory->title }}</option>
@endforeach
Or you could just have bothcategory
andsubcategory
in same table with extra flag namedparent_id
.
All parent category will have that value set to 0 and sub category will have the id of parent category inparent_id
column.
You can then simply store the value without any extra work.
Answer
Solution:
Set relation in modelApp\Category
(assuming there is a modelApp\Subcategory
)s:
public function subcategories()
{
return $this->hasMany('App\Subcategory', 'category_id','id');
}
Fetch categories with subcategories:
public function getCategories() {
$elements = Category::with('subcategories')->get();
return view('select', compact('elements'));
}
Generate select in view:
...
<div class="form-group">
<label for="exampleFormControlSelect1">Example select</label>
<select class="form-control" id="exampleFormControlSelect">
@foreach($elements as $element)
@if(count($element->subcategories) > 0)
<option disabled>{{ $element->title }}</option>
@foreach($element->subcategories as $subcategory)
<option>- {{ $subcategory->title }}</option>
@endforeach
@else
<option>{{ $element->title }}</option>
@endif
@endforeach
</select>
</div>
...
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: uncaught error: call to undefined function mysqli_connect()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.