@foreach
没有语句,代码运行良好。添加后,我收到以下错误:
Undefined variable: articles (View: C:\laravel\laravel\resources\views\about.blade.php)
$articles is undefined.
Make the variable optional in the blade template. Replace {{ $articles }} with {{ $articles ?? '' }}
当我添加?? ''
它时,它会产生错误:
Facade\Ignition\Exceptions\ViewException
Invalid argument supplied for foreach()
这是更大胆的完整代码: https ://github.com/matthoek/Articles
这是我的看法:
<? if (is_array($articles) || is_object($articles)) ?>
{
@foreach ($articles ?? '' as $article)
{
<li class = "first">
<h3>{{ $article->title}}</h3>
<p><a href="#">{{ $article->excerpt }}</a></p>
</li>
@endforeach
}
}
</ul>
这是我的控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Article;
class ArticlesController extends Controller
{
public function index()
{
$articles = App/Article::latest()->get();
//$articles = Review::all();
//$article = Review::all();
return view('articles.index',['articles'=>$articles]);
//return view('articles.index', ['articles' => $articles]);
}
public function show($id)
{
$article = App/Article::find($id);
//return view('articles.show', ['article' => $article]);
return view('articles.show')->with('article');
}
public function create()
{
return view('articles.create');
}
public function store()
{
//validation
//clean up
$article = new Article();
$article->title = request('title');
$article->excerpt = request('excerpt');
$article->body = request('body');
$article->save();
return redirect('/articles');
}
public function edit()
{
return view('articles.edit');
}
}
这是我的路由文件 web.php 的部分
Route::group(['middleware' => ['web']], function ()
{
Route::get('/about', function () {
$article = App\Article::latest()->get();
return view('about', compact('about', 'articles'));
//return $article;
});
}
我已将路由文件的部分更改为以下内容,但似乎不起作用。
return view('about')->with(['article'=> $article]);
我已确保以下内容在我app/Http/Kernel.php
的middlewareGroups
财产中web
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
我已将 foreach 循环更改为 each 循环,并且在线上出现相同的错误:
<h3>{{article->title}}</h3>
让我知道我是否应该发布更多代码。