Laravel with MongoDB CURD operations - part 3

You have already save data to post collection on mongodb.

Now we are going to display all the post in your web page.

We have already created the route /post to display all posts.
You need to use index method in your PostController to write a method to display all posts.
Now add following code to get all posts and display them in the view.

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::all();

        return view('posts.index')->with('posts', $posts);
    }

If you go to {YOUR_BASE_URL}/posts you will get an error as you haven't add index view yet.
Now will add the view.
Go to resources/views/posts and add a file "index.blade.php"
Add code like following to display your all posts title.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/css/style.css"></link>
</head>
<body>

<h3>All posts</h3>

<div class="container">
  <ul>
  @foreach($posts as $post)
    <li>{{ $post->title }}</li>
  @endforeach
  <ul>
</div>

</body>
</html>

Now browse {YOUR_BASE_URL}/posts and then you can see the list of your post titles.
You have almost done !
We will add link to post title /post/{id}. It will help us to see individual posts details.
Change your  <li>{{ $post->title }}</li> 
line to 
<li><a href="/posts/{{ $post->id }}">{{ $post->title }}</a></li>

Now you can see the link as well. In that link you can use to display post title and description.If you need display created date.
It is similar to display data here and give it a try by yourself.

Comments

Popular posts from this blog

Laravel with MongoDB CURD operations - part 2

Laravel with MongoDB CURD operations - part 1