Reputation: 57
I want to show a sidebar that displays data from the database across all my pages in Laravel, but I keep getting this error:
Undefined variable: products (View: C:\xampp\htdocs\shop\resources\views\pages\sidebar.blade.php) (View:
Sidebar
@extends('layouts.app')
<nav class=" d-none d-md-block bg-light sidebar">
<div class="sidebar-sticky">
<form>
<div class=" input-group">
<input class="form-control" type="text" placeholder="Search...">
<button type="submit" class="btn btn-primary" value="search">Search</button>
</div>
</form>
@foreach($products as $product)
<span id="catName">{{ $product->name }}</span>
<h2>No category to show</h2>
@endforeach
</div>
</nav>
Controller
public function index()
{
$product = Product::get();
return view('pages.sidebar', ['products' => $product]);
}
Route
Route::resource('sidebar','SidebarController');
app.blade.php
<div class="col-md-4 col-lg-4 col-sm-12">
@include('pages.sidebar')
</div>
Upvotes: 1
Views: 9480
Reputation: 141
You can either do @include()
or your can return it via a controller, you cannot do both. I think you might be a little mixed up with the structure of your project.
If you are using @include
it isn't going to hit a controller. So in theory, you would need to include ['products' => $products]
on every controller method.
Here is how I would do it:
sidebar.blade.php:
<nav class=" d-none d-md-block bg-light sidebar">
<div class="sidebar-sticky">
<form>
<div class=" input-group">
<input class="form-control" type="text" placeholder="Search...">
<button type="submit" class="btn btn-primary" value="search">Search</button>
</div>
</form>
@foreach($products as $product)
<span id="catName">{{ $product->name }}</span>
<h2>No category to show</h2>
@endforeach
</div>
</nav>
app.blade.php:
<div class="col-md-4 col-lg-4 col-sm-12">
@include('pages.sidebar')
</div>
Create a new file (or use an existing one) for a home page inside the pages folder, we will call it home.blade.php
home.blade.php:
@extends('layouts.app')
Change the view you are returning in the controller to new home.blade.php
file.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
$product = Product::get();
return view('pages.home', ['products' => $product]);
}
}
Upvotes: 2