passing multiple variable to one view in laravel 5.6

我只是一个虾纸丫 提交于 2021-01-29 10:44:23

问题


hello to all I want to pass multiple variables to one view this is my CategoryController.php

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

and this is SubCategoryController.php

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

this is my route for this action in web.php

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

and this is the view i am trying to do this 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

but i constantly see undefind vairalble alone they work good but when i want user both variables seee undefined vairable.


回答1:


Your site will go to the first route and will never go to your second controller. You should rather write.

Route

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

Controller

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

View

    @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



回答2:


you can write

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

or you can eager load this

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

in view

@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


来源:https://stackoverflow.com/questions/51836599/passing-multiple-variable-to-one-view-in-laravel-5-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!