Advertisement
Shell_Casing

PostController

Dec 25th, 2018
395
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. 'use strict'
  2.  
  3.  
  4.  
  5. // importing the model
  6. const Post = use('App/Models/Post');
  7.  
  8. // validator
  9. const { validate } = use('Validator')
  10.  
  11.  
  12. class PostController {
  13.  
  14. // index for all posts
  15. async allPosts({ view }) {
  16. const posts = await Post.all();
  17.  
  18.  
  19. return view.render('posts/allposts', {
  20. title: 'All user posts',
  21. posts: posts.toJSON()
  22. });
  23. }
  24.  
  25. // detail page for single post
  26. async postDetail({ params, view }) {
  27. const post = await Post.find(params.id);
  28.  
  29. return view.render('posts/detail', {
  30. post: post.toJSON()
  31. });
  32. }
  33.  
  34. // add a new post
  35. async addPost({ view }) {
  36. return view.render('posts/add');
  37. }
  38.  
  39. // store new post in the database
  40. async store({ request, response, session }) {
  41. const validation = await validate(request.all(), {
  42. title: 'required|min:2|max:255',
  43. body: 'required'
  44. });
  45.  
  46. if (validation.fails()) {
  47. session.withErrors(validation.messages()).flashAll();
  48. return response.redirect('back'); // reload the page
  49. }
  50.  
  51.  
  52. const post = new Post();
  53. post.Title = request.input('title');
  54. post.Content = request.input('content');
  55. await post.save();
  56.  
  57. session.flash({ notification: 'Post successfully saved!' });
  58.  
  59. return response.redirect('/posts');
  60. }
  61.  
  62.  
  63. }
  64.  
  65.  
  66. module.exports = PostController;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement