未定义的变量:Blade Laravel 6.4.0中的类别

我正在尝试使用下面的控制器在站点地图页面上显示我的类别。

CategoryController.php

class CategoriesController extends Controller
{
    public function create()
    {
        $categories = Category
                  ::orderBy('name','desc')
                  ->where('parent_id',NULL)
                  ->get();

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

以下是我的Blade文件的一部分,在其中使用Categories变量模板。

create.blade.php

<div class="form-group">
    <label for="exampleInputPassword1">Parent Category</label>
    <select name="parent_id" class="form-control">
        @foreach ($main_categories as $category)
            <option value="{{ $category->id }}">{{ $category->name }}</option>
        @endforeach
    </select>
</div>

我用各种方法来获取变量和传递,但是没有用,您有什么建议吗?

yutongxin 回答:未定义的变量:Blade Laravel 6.4.0中的类别

您在控制器中将集合命名为“类别”。要在您的视图中使用它,您需要使用相同的名称进行引用。

更改此:

// Your view is looking for a collection titled `main_categories`,which does not exist
@foreach ($main_categories as $category)
  <option value="{{ $category->id }}">{{ $category->name }}</option>
@endforeach

对此:

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

为了更加清楚,我将如下破坏代码并添加一些详细信息

    class CategoriesController extends Controller
{
    public function create()
    {
        $categories = Category
                  ::orderBy('name','desc')
                  ->where('parent_id',NULL)
                  ->get();
// Your are passing variable but I change it as below to be more clear

     //   return view('admin.category.create',compact('categories'));
//now you are passing the value to the view
          return view('admin.category.create',['categories' => $categories]);
    }
}

现在让我们在视图中捕获它。请注意,现在$ categories在视图中可用。如果您通过['A' => $categories],则视图具有$A变量,因此您应该调用在控制器中定义的相关变量。

   <div class="form-group">
        <label for="exampleInputPassword1">Parent Category</label>
        <select name="parent_id" class="form-control">
**{{-- In here you should pass $categories --}}**
            @foreach ($categories as $category)
                <option value="{{ $category->id }}">{{ $category->name }}</option>
            @endforeach
        </select>
    </div>
本文链接:https://www.f2er.com/3148526.html

大家都在问