这是来自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/