【问题标题】:Why I get "Undefined variable" in Laravel view?为什么我在 Laravel 视图中得到“未定义的变量”?
【发布时间】:2013-08-20 17:06:55
【问题描述】:

当我尝试从类别所在的表中获取数据时,我得到未定义的变量:类别错误。

$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 在您的视图中不可用,请尝试return View::make('posts.showcase', compact('posts','category'));

标签: php templates laravel undefined


【解决方案1】:

您没有将$category 变量传递给您的视图,您只是在传递$posts

换行:

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

成为:

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

您的$category 变量将可用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    相关资源
    最近更新 更多