php - undefined variable :$ Laravel 5

标签 php laravel

这是来自CategoriesController的代码:

 public function index()
{
    $categories = Category::all();
    return view('/home', compact('categories'));
}

这是我正在写的home.blade.php的代码
                @foreach($categories as $cat)
                @endforeach

然后在home.blade.php

我收到此错误:Undefined variable: categories
为什么会这样呢?一切都适用于Articles,但类别却没有问题,并且代码是相同的。

Home.blade.php
@extends('app')

@section('content')

     <div class="col-md-4 pull-right">
      <div class="panel panel-primary">
        <div class="panel-heading">
          <h3 class="panel-title">Categories</h3>
        </div>
        <div class="panel-body">

                          @foreach($categories as $cat)
                          <div class="col-lg-6">
                            <ul class="list-unstyled">
                                <li><a href="articles/category/{{  }}">News</a>
                                </li>
                            </ul>
                        </div>                          
                          @endforeach
   </div>
      </div>     
    </div>


  @if(count($articles))

    @foreach($articles as $article)

<div class="panel panel-default col-md-8">
  <div class="panel-heading">

  <h3>{{ $article->title }}</h3>
   <small>posted by <a href="users/{{ $article->author->name }}">{{ $article->author->name }}</a> {{ $article->created_at }}</small>
  </div>
  <div class="panel-body">
  {!! str_limit($article->body, 1000) !!} 
    <hr>
  <a href="{{ url('/articles/'.$article->slug) }}">Read More</a>   
  </div>
</div>

        @endforeach
    @else
        <h1>No articles at the moment.</h1>
    @endif
    <br>
    {!! $articles->render() !!}
@stop

最佳答案

你有两条路线

Route::get('/home', 'ArticlesController@index');
Route::get('/home', 'CategoriesController@index');

这意味着当您访问/ home时,仅触发ArticlesController @ index,而不会同时触发。

这意味着不会填充 View 中使用的$categories变量,因为您在CategoriesController中的index()方法旨在执行此操作,但从未被调用。

因此,您需要做这样的事情
Route::get('/home', 'HomeController@index');

public function index()
{
    $categories = Category::all();
    $articles   = Article::all();

    return view('/home', compact('articles', 'categories'));
}

关于php - undefined variable :$ Laravel 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31264242/

相关文章:

javascript - Vuejs 动态切换类在 Laravel Blade 模板中不起作用

php - 计算两个日期之间的天数而不重复

php - 仅 AJAX 访问

php - postgresql 中的最后三列值在通过 php laravel 发送时变为 null

javascript - 在 vuejs 中完成 @sumit.prevent 之后,有什么方法可以调用 onsumit 事件吗?

php - 干预 laravel 5

php - 使用 PDO 从 MySQL 数据库获取信息

javascript - 如何从 AJAX 获取两个返回变量

php - 如何将 mysql_query 结果的一列放入数组中?

laravel - Laravel,Openshift和错误消息