在Laravel 5.6中将多个变量传递给一个视图

时间:2018-08-14 08:05:14

标签: php laravel laravel-routing laravel-blade

您好,我想将多个变量传递给一个视图 这是我的CategoryController.php

    public function site()
{
    $categories = Category::all();
    return view('template.sitemap', ['categories' => $categories]);
}

这是SubCategoryController.php

public function index2(){
    $subcategories =  SubCategory::all();
    return view('template.sitemap',['subcategories'=>$subcategories]);
}

这是我在web.php进行此操作的路线

Route::get('sitemap.html','CategoryController@site')->name('sitemap')
Route::get('sitemap.html','SubCategoryController@index2')->name('sitemap');

这是我正在尝试执行的视图sitemap.blade.php

   @foreach($categories as $category)
      <li><a href="category.html">{{$category->name}}</a></li>
      <ul>
       @foreach($subcategories as $subcategory)
         <li><a href="category.html">{{$subcategory->category_name->name}</li>
       @endforeach
      </ul>
  @endforeach

但是我经常看到未定义的变态 他们一个人工作很好 但是当我要用户两个变量都看到不确定的可变性时。

2 个答案:

答案 0 :(得分:1)

你可以写

public function site()
{
    $categories = Category::all();
    $subcategories =  SubCategory::all();
    return view('template.sitemap', compact('categories', 'subcategories');
}

或者您可以急于加载

public function site()
{
    $categories = Category::with('subcategories')->get();
    return view('template.sitemap', compact('categories');
}

可见

@foreach($categories as $category)
  <li><a href="category.html">{{$category->name}}</a></li>
<ul>
    @foreach($category->subcategories as $subcategory)
         <li><a href="category.html">{{$subcategory->name}}</li>
    @endforeach   
   </ul>
@endforeach

答案 1 :(得分:0)

您的站点将转到第一个路由,并且永远不会转到第二个控制器。 你应该写。

路线

 Route::get('sitemap.html','CategoryController@site')->name('sitemap');

控制器

  public function site(){
      $data =  array();
      $data['subcategories']  =  SubCategory::all();
      $data['categories']     =  Category::all();
      return view('template.sitemap',compact("data"));
   }

查看

    @foreach($data['categories'] as $category)
    <li><a href="category.html">{{$category->name}}</a></li>
    <ul>
       @foreach($data['subcategories'] as $subcategory)
       <li><a href="category.html">{{$subcategory->category_name->name}}</li>
       @endforeach
    </ul>
    @endforeach