为什么我会得到“未定义的变量"?在Laravel视图中? [英] Why I get "Undefined variable" in Laravel view?

查看:473
本文介绍了为什么我会得到“未定义的变量"?在Laravel视图中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

when I try to fetch data from table where categories are I get Undefined variable: category error.

$ posts变量工作正常.

$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

但是当我尝试$ category时:

but when i try $category:

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

我得到一个错误.

我做错了什么?

这是来自我的PostsController

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'));
}

推荐答案

您没有将$category变量传递给视图,而只是传递了$posts.

You are not passing the $category variable to your view, you're just passing $posts.

更改您的行:

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

成为:

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

您的$category变量将可用.

这篇关于为什么我会得到“未定义的变量"?在Laravel视图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆