I’m working with Laravel 8 and I have made a resource Controller to return some results from MySQL table so index()
method of this Controller holds:
public function index() { $posts = Post::all(); return view('posts.index')->with('posts', $posts); }
At at index.blade.php
I added this:
@section('content') <h1>Posts</h1> @if(count($posts)>1) @foreach($posts as $post) <div class="well"> <h3>{{$post->title}}</h3> </div> @endforeach @endif @endsection
So as you can see, it look fine but the problem is it does not show me any output! I mean no results and no errors at all.
Here is also my table info:
However, on PHPStorm editor, the line return view('posts.index')->with('posts', $posts);
has a notice sign which is saying:
Extend retrun type from
IlluminateContractsFoundationApplication|IlluminateContractsViewFactory|IlluminateContractsViewView|IlluminateHttpResponse|IlluminateViewView
But I don’t what does it mean?
So if you know how to solve this problem, please let me know, I would really appreciate any idea from you guys.
Advertisement
Answer
I feel like the issue here is a simple logic issue. On the line where you check for the count of the $posts
variable using @if(count($posts)>1)
, the if condition would fail if you have only one post in your database. This is because 1 is not greater than 1
. You wouldn’t see anything in your view even though there is one post in your database. To fix the issue, modify your code to this:
@if(count($posts) > 0)
OR
@if(count($posts) >= 1)