Laravel动态相关下拉列表

时间:2018-08-30 14:24:59

标签: laravel forms

我需要添加一个Laravel动态相关下拉列表。我很困惑.. 在我的数据库中,我同时拥有类别及其子类别。

  • Account_id = 0 =>类别
  • Account_id = 1 => ID为= 1的类别或子类别的子类别
  • Account_id = 2 => id为= 2的类别或子类别的子类别

这是我的实际代码:

方法:

 public function index()
 {
    $categories = Account::where('account_id', '=', 0)->get();
    $allCategories = Account::where('account_id', '=', 0)- 
  >pluck('account_name','id');
     return view('Account.list',compact('categories', 'allCategories')); // 
  set the path of you templates file.

  }

public function children(Request $request)
{
    return Account::where('account_id', $request->account_id)->pluck('account_name', 'id');
}

查看:

                                 <div class="form-group">
     {!! Form::label('account_id', 'Parent Category:')!!}
     {!! Form::select('account_id', $allCategories,  ['placeholder' => 
     'Choose Category'])!!}
        </div>


                                <div class="form-group">
     {!! Form::label('children', 'Child category:')!!}
     {!! Form::select('children', [], null, ['placeholder' => 'Choose child 
     category'])!!}
    </div>

路线:

Route::get('/categories', [
   'uses' => 'AccountController@index',
   'as' => 'categories'
 ]);
 Route::get('/categories/children', [
   'uses' => 'AccountController@children',
   'as' => 'categories.children'
 ]);

JS:

 <script>
$('#account_id').change(function(e) {
    var parent = e.target.value;
    $.get('/categories/children?account_id=' + account_id, function(data) {
        $('#children').empty();
        $.each(data, function(key, value) {
            var option = $("<option></option>")
                  .attr("value", key)                         
                  .text(value);

            $('#children').append(option);
        });
    });
});
</script>

1 个答案:

答案 0 :(得分:1)

首先尝试创建新的route

Route::post('subchildren/youcontroller', [
  'as'   => 'children.categories',
  'uses' => 'youUrlController\yourController@childrenCategory',
]);

下一步创建route转到controller创建新的method

public function childrenCategory(Request $request) 
{
   try {
     $subCategory= subCategory::where('category_id', $request->nameSelectCategoryinYourView)->get();
      return response()->json(['subCategory' => $subCategory], 200);
   } catch (Exception $e) {
      return response()->json(['error' => 'Error'], 403);
  }
}

下一步view

<div class="form-group  m-b-40">
  <select name="subCategory" class="form-control p-0" id='subCategory'></select>
</div>

下一步javascript

jQuery(document).ready(function($) {
 $('#FirstSelect').change(function () {
    $('#subCategory').empty();
    var Category = $(this).val();

    datos = {
      tipo : Category
    },

    $.ajax({
      url: '{{ route('children.categories') }}',
      type: 'POST',
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      data: datos,
      success: function (argument) {

        arreglo = {id:"a", tipo:""};
        argument.detalles.unshift(arreglo); 

        $.each(argument.subCategory, function(index, el) {

          var opcion = '<option value="'+ el.id +'">'+ el.subCategoryName+'</option>';
          $('#subCategory').append( opcion );
        });
      }
    })
    .done(function() {
      console.log("success");
    })
    .fail(function() {
      console.log("error");
    })
    .always(function() {
      console.log("complete");
    });
  })
 });
});
相关问题