我在我的視圖中有兩個頁面檔案,首先是我的home blade,然后是第二個category blade,它們都使用extends asidenav
我的問題是當我重定向到類別檔案時它給了我一個錯誤Undefined variable: categories,但是當我重定向它時在我的主檔案中它作業正常。我將描述我的代碼。
在我的控制器中,HomeController我將一個資料傳遞 categories給home.blade.php
class HomeController extends Controller
{
public function home()
{
$categories = Category::select('id','name')->get();
return view('home', compact('categories'));
}
public function category(){
return view('category');
}
}
我的輸出home.blade.php
@extends('asidenav')
@section('section')
<main>
this is homepage
</main>
@endsection
你可以在我家的刀片中看到有一個延伸的 sidenav。在我的 sidenav 內部擴展了我傳遞的資料類別在該 sidenav 內部以制作類別串列
我的輸出擴展
了我傳遞的資料categories
<ul>
@foreach($categories as $category)
<li><a href="{{ route('category',$category->id) }}"><span>{{ $category->name }}</a>
@endforeach
</ul>
當我單擊ahref重定向類別刀片時,它會給出錯誤未定義的變數類別。但是當我重定向到家庭刀片時,它正在作業我的輸出category.blade.php
@extends('asidenav')
@section('section')
<main>
this is category
</main>
@endsection
但是當我在我的類別控制器中嘗試這段代碼時,它作業正常未定義變數類別的錯誤未顯示
public function category()
{
$categories = Category::select('id','name')->get();
return view('category', compact('categories'));
}
我的意思是我只想通過data categories我的家庭刀片和其他檔案刀片中的單個檔案,props但我不知道如何做到這一點
uj5u.com熱心網友回復:
您可以創建一個服務提供者來負責注入這些變數,而無需在您的控制器中宣告它們,在您的引導方法中:
use Illuminate\Support\Facades\View;
View::composer(['asidenav', 'home'], function($view){
$categories = Category::all();
return $view->with('categories', $categories);
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/494313.html
標籤:拉拉维尔 laravel-5 laravel-8 laravel-7
上一篇:Laravel控制器查詢
