laravel undefine变量:category

时间:2017-03-05 20:42:26

标签: php laravel

请帮帮我;我是Laravel的新手,我不知道我做错了什么。

这是我的视图

<div class="container">
  <h1>category and subcategory</h1>
  <div class="row">
    <div class="col-md-10 col-md-offset-1">
      {!! Form::open(array('url' => '','files'=>true)) !!} {!! Form::token(); !!}
      <div class="form-group">
        <label for="">category</label>
        <select class="form-control input-sm" name="" id="">
          @foreach ( $category as $category)
          <option value="{{$category->id}}">{{$category->name}}</option>
          @endforeach
        </select>
      </div>
      <div class="form-group">
        <label for="">subcategory</label>
        <select class="form-control input-sm" name="" id="">
          <option value=""></option>
        </select>
      </div>
      </form>
    </div>
  </div>
  <script type="text/javascript">
    $(document).ready(function() {
          $("#category").on('change', function(e) {
            console.log(e);
            var cat_id = e.target.value;
            $.get('/ajax-subcat/' + cat_id, function(data) {
              //success data
              console.log(data);
            })
          });
  </script>
</div>
</div>
</div> 

这是路线

Route::get('/', function() {
  $category = \App\ category::all();
  return view('layouts.app') - > with('categories', $category);
});
Route::get('/ajax-subcat', function() {
  $category = \App\ category::all();
  $cat_id = Input::get('cat_id');
  $subcategory = subcategory::where('category_id', '=', $cat_id) - > orderBy('name', 'asc') - > get();
  return response() - > json($subcategory);
});

这是我的错误日志文件:

  

ec195dc7ec967851481b4815c28c6879244d5d45.phpline 87中的ErrorException:               未定义的变量:category(查看:C:\ xampp \ htdocs \ laravel \ resources \ views \ layouts \ app.blade.php)(查看:C:\ xampp \ htdocs \ laravel \ resources \ views \ layouts \ app.blade。 PHP)           在ec195dc7ec967851481b4815c28c6879244d5d45.php第87行           at CompilerEngine-&gt;在PhpEngine.php第44行中的handleViewException(object(ErrorException),'1')               在PhpEngine -

造成这些错误的原因是什么?

1 个答案:

答案 0 :(得分:1)

尝试更改:

@foreach ( $category as $category)

为:

@foreach ( $categories as $category)

希望这有帮助!