Home > Mobile >  I'm having trouble placing a variable in my controller [duplicate]
I'm having trouble placing a variable in my controller [duplicate]

Time:10-07

I created an ecommerce store using Laravel, where I added all the controllers and the routes which seem to be working well without any errors. But recently I've been trying to add other 'related products' to my website. But when I ran the website after adding it, I get the error

'Undefined variable:categories'.

I've already placed the routed in my controller and allocated it the variable product. The only thing I don't know is how I would add another variable to the controller. I've tried nearly everything but nothing seems to work up to now. Here's my code.

<!--Related Products-->
<div class="col-md-4">
            <ul class="list-group list-group-horizontal-md">
                <li class="list-group-item active">
                    Related Products
                <li>
                    @foreach($categories as $category)
                        <a href="{{route("category.products"),$category->slug}}" class="list-group list-group-horizontal-md list-group-item-action">
                            {{$category->title}}
                            ({{$category->product->count()}})
                        </a>
                    @endforeach
            </ul>
        </div>
<!--Related Products-->

Controller

public function show(Product $product)
{
    //
    return view('products.show')->withProduct($product);
}

//Category Model

public function products(){
    return $this->hasMany(Product::class);
}

public function getRouteKeyName(){
    return 'slug';
}

Routes

Route::get('/ourbooks', [App\Http\Controllers\OurbooksController::class, 'ourbooks'])->name('ourbooks');
Route::get('/category/products/{category}', 'App\Http\Controllers\OurbooksController@getCategoryProducts')->name('category.products');
Route::resource('/products','App\Http\Controllers\ProductController');
Route::resource('/orders','App\Http\Controllers\OrderController');

Can any help me and show me how to get rid of the error?

CodePudding user response:

=>compact tree variable.

public function show(Product $product,Category $category)
{
    $categories = Category::all();
    return view('products.show',compact('categories','product','category'));
}

CodePudding user response:

You must also get and transfer categories in the controller as follows:

public function show(Product $product)
{
    //
    $categories = Category::all();
    return view('products.show',compact('categories'))->withProduct($product);
}

  • Related