我试图从laravel刀片的布局中产生一个部分,但问题是当我yeild它时 undefined var

这是我的代码:

web.php:

Route::get('/pr','ProductController@carousel');

产品 Controller :
    public function carousel()
    {
        $Proudcts= Product::select('name','amount','dis_amount','stock','company_id','category_id','pic_url')->get();
        return view('product-carousel')->with('products', $Proudcts);
    }

product-carousel.blade.php:
@include('include.head')
<body>
@section('product-carousel')
<div class="owl-carousel owl-theme">
@foreach($products as $product)
<div class="product-carousel item ">
    <a>
        <img  src="{{$product->pic_url}}" style='height: 400px; width: 100%; object-fit: contain'/>
        <h4 lang="en_US" class="product-name-show">{{$product->name}}</h4>
        <h3 class="amount-for-product">
            Buy
        </h3>
    </a>
</div>
@endforeach
</div>
<script src="/js/owl.js" type="text/javascript" language="JavaScript"></script>
@endsection
</body>
</html>

index.blade.php:
@include('include.head')
@extends('product-carousel')
@yield('product-carousel')

如您所见,我在“index.blade.php”中扩展了“product-carousel.blade.php”,并添加了“@section('product-carousel')” eil问题是 $ products 在“index.blade.php”

但正在“product-carousel.blade.php”中工作

这是错误:
undefined variable :产品

最佳答案

如果希望在存在 View 时使变量可用,请在AppServiceProviderboot函数中使用 View 编辑器

public function boot()
{
    view()->composer(['index', 'product-carousel'], function ($view) {
        $products = \App\Product::select('name', 'amount', 'dis_amount', 'stock', 'company_id', 'category_id', 'pic_url')->get();
        return $view->with('products', $products);
    });
}

希望这可以帮助

关于php - 布局中的 undefined variable 错误(Laravel),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58422495/

10-13 08:02
查看更多