Laravel未定义变量

Laravel未定义变量

本文介绍了Laravel未定义变量$ articles的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正忙于自己的新闻系统,正在使用Laravel5.我对Laravel并不陌生,并使用教程逐步学习.现在,我遇到此错误未定义的变量:文章".

I'm busy with my own news system and I'm using Laravel 5. I'm quite new to Laravel and using tutorials to walk my way through it. Now I'm having this error "Undefined variable: articles".

这是我的ArticlesController.php

Here is my 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

Here is my 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

我尝试了几件事,例如删除所有内容并重新开始.真正的窍门什么都没有.

I have tried couple things, such as removing everything and starting over. Nothing really did the trick.

推荐答案

您必须将变量传递给视图,否则视图不会知道"该变量.像这样:

You have to pass the variable to your view, else the view does not "know" the variable. Like this:

<?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(),]);
    }
}

参考此处.

这篇关于Laravel未定义变量$ articles的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:14