Route.get('posts/:id', 'PostsController.show')
You are viewing the legacy version of AdonisJS. Visit https://adonisjs.com for newer docs. This version will receive security patches until the end of 2021.
Let’s finish up this tutorial by making final changes to the entire flow. Intentionally it was a simple tutorial to make you feel comfortable with the framework.
We have got a view listing all the blog posts. But there is no way to view a single blog post. So quickly open the routes file and register a route for same.
Route.get('posts/:id', 'PostsController.show')
The id
is a dynamic segment to pass the post id in the URL and access it from the controller. You can read more about Route parameters in the docs.
Next, we need to create the view for showing a post.
./ace make:view posts/show
create: resources/views/posts/show.njk
Paste the below code snippet to the showPost view.
{% extends 'master' %}
{% block content %}
<div class="post">
<div>
<a href="/"> Go Back </a>
</div>
<hr>
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
</div>
{% endblock %}
Finally, we need the PostsController.show
method to fetch the post from the database and send to it view.
'use strict'
class PostsController {
* show (request, response) {
const post = yield Post.find(request.param('id'))
yield response.sendView('posts.show', { post: post.toJSON() })
}
}
This time, we make use of the find
method to fetch the post for a given id, and finally, we send the json representation of the post to the view. We are not done yet. Let’s open the home.njk view and add the link to the individual post.
<h2><a href="posts/{{ post.id }}"> {{ post.title }} </a></h2>
Now refresh the browser and click on the individual posts to view a particular post.
So far we have been visiting post/create
route manually to create a new post. Let’s add a link on the home page. Paste the below code snippet just before the posts-wrapper div.
<div>
<p>
Below is the list of all the awesome posts created by all of us. You can also
contribute by clicking the below button.
</p>
<a href="posts/create" class="btn btn-success btn-block"> Create New Post </a>
<hr>
</div>
Now, we have a big shiny button linked to the post create route.
Another thing we should fix is to list the posts in desc order, so that the recent post always shows on the top.
'use strict'
class PostsController {
* index (request, response) {
const posts = yield Post.query().orderBy('id', 'desc').fetch()
yield response.sendView('home', { posts: posts.toJSON() })
}
}
Now refresh the page and you will find the most recent post on the top instead of bottom.