php 为什么我在 Laravel 视图中得到“未定义的变量”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18341009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why I get "Undefined variable" in Laravel view?
提问by milos
when I try to fetch data from table where categories are I get Undefined variable: category error.
当我尝试从类别所在的表中获取数据时,出现未定义变量:类别错误。
$posts variable work fine.
$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
but when i try $category:
但是当我尝试 $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
这是来自我的 PostsController
public function showcase()
{
$category = Category::all();
$posts = Post::with('category')->orderBy('updated_at')->get();
return View::make('posts.showcase', compact('posts'));
}
回答by Rubens Mariuzzo
You are not passing the $category
variable to your view, you're just passing $posts
.
您没有将$category
变量传递给您的视图,您只是将$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.
您的$category
变量将可用。