Wednesday, March 1, 2017

How to populate

I have 2 tables, CATEGORIES and SUBCATEGORIES.

In my Eloquent Model I have this:

class Category extends Model
{
    public function subcategories()
    {
        return $this->hasMany('App\Subcategory');
    }
}


class Subcategory extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }

}

This is my Controller:

class CourseController extends Controller
{

    public function create()
    {
        $categories = Category::all();

        return view('course.create' , compact('categories'));
    }
}

So I have 2 select tag, one from CATEGORY, and the other is for Subcategory.

<div class="form-group">
        <label class="control-label col-sm-2" for="category">Category:</label>
        <div class="col-sm-10">
            <select class="form-control" name="category" id="category">
                @foreach($categories as $category)
                    <option value=""></option>
                @endforeach

            </select>
        </div>
     </div>
 <div class="form-group">
        <label class="control-label col-sm-2" for="subcategory">SubCategory:</label>
        <div class="col-sm-10">
            <select class="form-control" name="subcategory" id="subcategory">               
                    <option value=""></option>      
            </select>
        </div>
     </div>

Now my question is, how to populate the SUBCATEGORY select options if ever I will click one of the category?

For example: I will choose the "Web Development" category, then the second dropdown(select tag) will only display "PHP,HTML,CSS" subcategories.




via Vahn Marty

Advertisement