问题
when I try to fetch data from table where categories are I get Undefined variable: category error.
$posts variable work fine.
@if(count($posts))
@foreach($posts as $post)
@if($post->category)
<div class="{{ $post->category->name }} isotope-item">
<img src="../img/showcase/1.jpg" alt="">
<div class="disp-post">
<span class="icon"></span>
<p class="time">{{ $post->updated_at }}</p>
<h4>{{ Str::words($post->title, 3) }}</h4>
<p>{{ Str::words($post->body, 60) }}</p>
<p class="link">{{ HTML::linkRoute('posts.show', 'Read more', array($post->id)) }}</p>
</div>
</div>
@endif
@endforeach
@endif
but when i try $category:
@if(count($category))
@foreach($category as $c)
<li><a href="#" data-filter="{{ $c->name }}">Networking</a></li>
@endforeach
@endif
I get an error.
What am I doing wrong?
This is from my PostsController
public function showcase()
{
$category = Category::all();
$posts = Post::with('category')->orderBy('updated_at')->get();
return View::make('posts.showcase', compact('posts'));
}
回答1:
You are not passing the $category
variable to your view, you're just passing $posts
.
Change your line:
return View::make('posts.showcase', compact('posts'));
To be:
return View::make('posts.showcase', compact('posts', 'category'));
And your $category
variable will be available.
来源:https://stackoverflow.com/questions/18341009/why-i-get-undefined-variable-in-laravel-view