Why I get “Undefined variable” in Laravel view?

≯℡__Kan透↙ 提交于 2019-12-07 13:27:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!