2013-08-20 78 views
3

当我尝试从表中获取数据的类别时,我得到未定义变量:类别错误。为什么我在Laravel视图中显示“未定义变量”?

$ 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 

但是当我尝试$类别:

@if(count($category)) 
    @foreach($category as $c) 
     <li><a href="#" data-filter="{{ $c->name }}">Networking</a></li> 
    @endforeach 
@endif 

我得到一个错误。

我在做什么错?

这是从我的PostsController

public function showcase() 
{ 
    $category = Category::all(); 
    $posts = Post::with('category')->orderBy('updated_at')->get(); 
    return View::make('posts.showcase', compact('posts')); 
} 
+1

你收到错误,因为'$ category'在你看来不可用,试着'返回View :: make('posts.showcase',compact('posts','category'));' –

回答

7

你是不是传递$category变量视图,你只是路过$posts

更改行:

return View::make('posts.showcase', compact('posts')); 

为:

return View::make('posts.showcase', compact('posts', 'category')); 

而且你$category变量将可用。