问题
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