Laravel未定义变量$文章

时间:2017-10-17 09:38:48

标签: php laravel

我正在忙于自己的新闻系统而且我正在使用Laravel 5.我对Laravel很新,并使用教程来完成它。现在我有这个错误“Undefined variable:articles”。

这是我的ArticlesController.php

<?php
namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;

class ArticlesController extends Controller
{
    public function index()
{
    return view('pages.news');
    }
}

这是我的news.blade.php

@foreach ($articles as $article)
<!-- Post -->
<div class="blog-item">
    <!-- Post title -->
    <h2 class="blog-item-title font-alt">
        <a href="news-single.html">{{ $article->title }}</a>
    </h2>
    <!-- Post data -->
    <div class="blog-item-data">
        <a href="#"><i class="fa fa-clock-o"></i> 5 December</a>
        <span class="seperator">&nbsp;</span>
        <a href="#"><i class="fa fa-user"></i> John Doe</a>
        <span class="seperator">&nbsp;</span>
        <i class="fa fa-folder-open"></i>
        <a href="#">Category</a>, <a href="#">Category</a>
        <span class="seperator">&nbsp;</span>
        <a href="#"><i class="fa fa-comments"></i> 5 Comments</a>
    </div>
    <!-- Media gallery -->
    <div class="blog-media">
        <ul class="clearlist content-slider">
            <li><img src="images/portfolio/full-project-1.jpg" alt="Blog image"></li>
        </ul>
    </div>
    <!-- Text intro -->
    <div class="blog-item-body">
        <p>{{ $article->body }}</p>
    </div>
    <!-- Read more -->
    <div class="blog-item-foot">
        <a href="news-single.html" class="btn btn-mod btn-round btn-small">Read More <i class="fa fa-angle-right"></i></a>
    </div>
</div>
@endforeach

我尝试了几件事,比如删除所有内容并重新开始。没有什么可以做到的。

2 个答案:

答案 0 :(得分:5)

您必须将变量传递给您的视图,否则视图不会知道&#34;变量。像这样:

<?php
namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;

class ArticlesController extends Controller
{
    public function index()
    {
        return view('pages.news', ['articles' => Article::all(),]);
    }
}

参考here

答案 1 :(得分:2)

您不会将任何数据从控制器传递到视图,因此请执行以下操作:

$articles = Article::get();

return view('pages.news', ['articles' => $articles]);

或者:

return view('pages.news', compact('articles'));

或者:

return view('pages.news')->with('articles', $articles);

https://laravel.com/docs/5.5/views#passing-data-to-views