当我尝试从表中获取类别的数据时,我得到未定义的变量:类别错误.
$posts变量工作正常.
@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
但是当我尝试$category时:
@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')); }
解决方法
你没有将$category变量传递给你的视图,你只是传递$posts.
改变你的行:
return View::make('posts.showcase',compact('posts'));
成为:
return View::make('posts.showcase',compact('posts','category'));
您的$category变量将可用.