未定义的变量:$ Laravel 5

zlo*_*tte 2 php laravel

这是CategoriesController的代码:

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

这是我写的代码 home.blade.php

                @foreach($categories as $cat)
                @endforeach
Run Code Online (Sandbox Code Playgroud)

然后在 home.blade.php

我收到这个错误: Undefined variable: categories

为什么会这样?一切都适用于文章而不是类别,代码是相同的.

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
Run Code Online (Sandbox Code Playgroud)

Ben*_*rne 9

你有两条路线

Route::get('/home', 'ArticlesController@index');
Route::get('/home', 'CategoriesController@index');
Run Code Online (Sandbox Code Playgroud)

这意味着当你访问/ home时,只会触发ArticlesController @ index,而不是两者.

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

因此你需要做这样的事情

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

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

    return view('/home', compact('articles', 'categories'));
}
Run Code Online (Sandbox Code Playgroud)