Laravel 8 不显示来自数据库的数据
Laravel 8 Does Not Show Data From DB
我正在与 Laravel 8 合作,我已经为 return 一些来自 MySQL table 的结果创建了一个资源控制器,所以 index()
这个方法控制器持有:
public function index()
{
$posts = Post::all();
return view('posts.index')->with('posts', $posts);
}
在 index.blade.php
我添加了这个:
@section('content')
<h1>Posts</h1>
@if(count($posts)>1)
@foreach($posts as $post)
<div class="well">
<h3>{{$post->title}}</h3>
</div>
@endforeach
@endif
@endsection
如您所见,它看起来不错,但问题是它没有显示任何输出!我的意思是没有结果,也没有错误。
这也是我的 table 信息:
但是,在 PHPStorm 编辑器上,行 return view('posts.index')->with('posts', $posts);
有一个通知标志,上面写着:
Extend retrun type from
\Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response|\Illuminate\View\View
但我不知道这是什么意思?
因此,如果您知道如何解决此问题,请告诉我,我将不胜感激。
我觉得这里的问题是一个简单的逻辑问题。在使用 @if(count($posts)>1)
检查 $posts
变量计数的那一行,如果数据库中只有一个 post,则 if 条件将失败。这是因为 1 is not greater than 1
。即使您的数据库中有 post,您也不会在视图中看到任何内容。要解决此问题,请将您的代码修改为:
@if(count($posts) > 0)
或
@if(count($posts) >= 1)
首先,您应该在控制器本身中使用 dd($posts) 或 return $posts 检查 $posts 变量是否有数据。如果 dd 或 return 有数据,则在 blade 文件中检查相同的数据。
而不是使用 @if(count($posts) > 0) 你应该使用 @if(isset($posts)).
我正在与 Laravel 8 合作,我已经为 return 一些来自 MySQL table 的结果创建了一个资源控制器,所以 index()
这个方法控制器持有:
public function index()
{
$posts = Post::all();
return view('posts.index')->with('posts', $posts);
}
在 index.blade.php
我添加了这个:
@section('content')
<h1>Posts</h1>
@if(count($posts)>1)
@foreach($posts as $post)
<div class="well">
<h3>{{$post->title}}</h3>
</div>
@endforeach
@endif
@endsection
如您所见,它看起来不错,但问题是它没有显示任何输出!我的意思是没有结果,也没有错误。
这也是我的 table 信息:
但是,在 PHPStorm 编辑器上,行 return view('posts.index')->with('posts', $posts);
有一个通知标志,上面写着:
Extend retrun type from
\Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response|\Illuminate\View\View
但我不知道这是什么意思?
因此,如果您知道如何解决此问题,请告诉我,我将不胜感激。
我觉得这里的问题是一个简单的逻辑问题。在使用 @if(count($posts)>1)
检查 $posts
变量计数的那一行,如果数据库中只有一个 post,则 if 条件将失败。这是因为 1 is not greater than 1
。即使您的数据库中有 post,您也不会在视图中看到任何内容。要解决此问题,请将您的代码修改为:
@if(count($posts) > 0)
或
@if(count($posts) >= 1)
首先,您应该在控制器本身中使用 dd($posts) 或 return $posts 检查 $posts 变量是否有数据。如果 dd 或 return 有数据,则在 blade 文件中检查相同的数据。
而不是使用 @if(count($posts) > 0) 你应该使用 @if(isset($posts)).