Pedro
Pedro

Reputation: 1477

Select category with 2 levels (category and subcategory)

im creating a select categories with 2 leves, a category and subcategory, i already creting and saving the data in the database, the only thing missing is in the view page, make the select field appear how i expect, but im having some doubts in how sould it be, can someone give a hint?

code example:

categories:
- id;
- name;
- parent_id;

example data:
1,  Politics, null;
2, Sports, null;
3, World, null;
4, Soccer, 2;

Final result on Input Select:
Politics
Sports
-- Soccer
World


my view:
<select  name="category" id="category" class="form-control">
                                <option>Select...</option>
                                  @foreach($categories as $category)
                                    <option value="{{$category->id}}">{{$category->name}}</option>

                                  @endforeach
                              </select>

Upvotes: 0

Views: 1723

Answers (1)

Amit Gupta
Amit Gupta

Reputation: 17658

Create a relation between categories as:

Category Model

public function subcategories()
{
    return $this->hasMany('App\Category', 'parent_id');
}

public function parent()
{
    return $this->belongsTo('App\Category');
}

Then you can query it as:

$Categories = Category::whereNull('parent_id')->with('subcategories')->get();

In your view, you can do as:

@foreach($categories as $category)
  <option value="{{$category->id}}">{{$category->name}}</option>
  @foreach($category->subcategories as $subcategory)
    <option value="{{$subcategory->id}}">{{$subcategory->name}}</option>
  @endforeach
@endforeach

Upvotes: 3

Related Questions