vendredi 18 décembre 2015

Selecting a sub-category after selecting category using laravel

I am creating a form in which I get subcategories after I select one category. But problem is that I have only one table in which categories and subcategories are stored.

All the values in the table have their auto-increment id and a parent_id. For all Main-Categories, parent_id is 0. and Sub-categories have Main-Categories id as their parent_id. As shown in image

enter image description here

Depending upon this condition I build a query and passed that query to my view through controller as

$k = DB::table('main_category')->where('parent_id','=','0')->lists('name','id');

And in view:

<div class="form-group">
    {!! Form::label('category','Category:') !!}
    <select name="category" id="category" class="form-control input-sm">
        @foreach($k as $a)
        <option value="{{$a}}">{{$a}}</option>
            @endforeach
    </select>
</div>

<div class="form-group">
    {!! Form::label('subcategory','Subcategory:') !!}
    <select name="subcategory" id="subcategory" class="form-control input-sm">
            <option value=""></option>
    </select>
</div>

My script.js:

    $('#category').on(change,function(e){
  console.log(e);
   var cat_id = e.target.value;

    //ajax
    $get('/ajax-subcat?cat_id='+ cat_id,function(data){
        //success data
        //console.log(data);
        $('#subcategory').empty();
        $.each(data,function(index,subcatObj){
            $('#subcategory').append('<option value ="'+subcatObj.id+'">'+subcatObj.name+'</option>');
        });

    });
});

Routes.php:

    Route::resource('event', 'EventsController');

Route::get('/ajax-subcat',function () {
    $cat_id = Input::get('cat_id');
//    return $cat_id;
    $subcategories = DB::table('main_category')->where('name', '=',$cat_id)->get();
    return Response::json($subcategories);
});

But when I use $a->name or $a->id, I get error as trying to get non object property.

Also, I am taking refrence of this video



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire