public function press (Request $request)
{
if($request->has('search')){
$articles = Press::search($request->input('search'))->get();
}
return view('pages.press.index', compact('articles'));
}
我收到错误Undefined variable: articles
。以上是我在我的控制器中使用的代码。我犯的错误是什么?
查看
@if(!empty($articles))
@foreach ($articles as $article)
<div class="col-md-4">
<div class="box border">
<div class="box-header">
<a href="{{ url('/press/'.$article->slug) }}"><img src="{{ url('http://assets.hobohweb.com/uploads/press/'.$article->image) }}" class="img-fluid" alt=""></a>
</div>
<div class="box-body">
<a href="{{ url('/press/'.$article->slug) }}"><h6 class="h-2x">{{ $article->title }}</h6></a>
{{ Carbon\Carbon::parse($article->created_at)->diffForHumans() }} on <a href="{{ url($article->source_url) }}" class="text-primary">{{ $article->source }}</a>
</div>
</div>
</div>
@endforeach
@endif
答案 0 :(得分:1)
您在if
内声明变量,但如果条件为false,则永远不会设置变量。尝试使用else
条件:
public function press (Request $request)
{
if($request->has('search')){
$articles = Press::search($request->input('search'))->get();
} else {
$articles = null;
}
return view('pages.press.index', compact('articles'));
}
您还需要检查视图中$articles
是否为空。
答案 1 :(得分:1)
这是因为变量从未被赋值,并且在-if
的外部上下文中不存在尝试使用此
public function press (Request $request)
{
$articles = array();
if($request->has('search')){
$articles = Press::search($request->input('search'))->get();
}
return view('pages.press.index', [
'articles' => $articles
]);
}
查看
@foreach ($articles as $article)
<div class="col-md-4">
<div class="box border">
<div class="box-header">
<a href="{{ url('/press/'.$article->slug) }}"><img src="{{ url('http://assets.hobohweb.com/uploads/press/'.$article->image) }}" class="img-fluid" alt=""></a>
</div>
<div class="box-body">
<a href="{{ url('/press/'.$article->slug) }}"><h6 class="h-2x">{{ $article->title }}</h6></a>
{{ Carbon\Carbon::parse($article->created_at)->diffForHumans() }} on <a href="{{ url($article->source_url) }}" class="text-primary">{{ $article->source }}</a>
</div>
</div>
</div>
@endforeach
我希望这可以帮到你
答案 2 :(得分:1)
只需检查搜索中是否有文章,例如:
if($request->has('search')){
$articles = Press::search($request->input('search'))->get();
} else {
$articles = [];
}
并在视图中使用它:
@forelse($articles as $article)
...
@empty
<p>There are no articles!</p>
@endforelse