Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined variable error in Layouts (Laravel)

im trying to yield a section from a layout in laravel blade but the problem is the var is not defined when i yeild it

here is my code:

web.php:

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

ProductController:

    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')

as you can see i extends "product-carousel.blade.php" in "index.blade.php" and yeild the "@section('product-carousel')" ، the problem is $products is not exist in "index.blade.php"

But is working in the "product-carousel.blade.php"

here is the error : Undefined variable: products

like image 324
yosober Avatar asked Dec 19 '25 22:12

yosober


1 Answers

If you want a variable to be available whenever a view is present, use view composers, in AppServiceProvider's boot function

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);
    });
}

Hope this helps

like image 179
Salim Djerbouh Avatar answered Dec 21 '25 12:12

Salim Djerbouh