I'm trying to make a posting system, with a resource routing combination on the posts. When I try to run the app to view the posts, it returns an error stating that the posts could not be found within the view. I have the controller code for the index and the show functions:
public function index()
{
$posts = Post::latest()->get();
return view('view', compact('posts'));
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
The view that I have for the app uses the post variable to display the posts:
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-2">
<div class="panel panel-default">
<!-- Posts will be displayed on the same panel -->
<div class="panel-body" id="view">
@foreach($posts as $post)
<article id="post">
<a href="/view/posts{{ $post->id }}">
{{ $post->title }}
</a>
<div class="body">
{{ $post->body }}
</div>
<!-- Footer for posts will include interaction features -->
</article>
@endforeach
</div>
</div>
</div>
</div>
</div>
Is there something that the laravel installation isn't doing correctly? Is the compact function set up correctly?
The return of the index action is wrong
return view('view', compact('posts'));
Change 'view' with 'posts'
Your controller index function should be something like this:
public function index()
{
$posts = Post::get();
return view('posts.index', compact('posts'));
}
Use compact('posts')
If you're a beginner checkout the laracasts video series to get a good understanding of the Laravel framework.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.