Laravel 5.4 #17 : Add comments to posts

We are going to add the possibility for logged users to comment on posts.

First, we have to add the comments table in the database. For that, as always, we have to create a migration:

With this code:

And execute it.

 

Once we have this, we have to create the controller and the model for the comments. Laravel allows us to do this simply with one command:

Open the  Comment.php model:

Add the relationships with comments in the Post.php and  User.php models:

When you have this, we can access the comments of a posts and a user’s comments easily.

 

Open the controller and add the following code:

We only add the store method, which is the one that creates the comment in the database, later we will add more functionalities.

Before continuing, we must modify the route that shows the detail of a post and add a name:

 

Now, we create the Form Request to validate the information sent of the comment we want to insert ( php artisan make:request CommentRequest) and add this code:

Check that the user is logged in and that the comment has content and that it is maximum 1000 characters.

Add the route:

If you look, we have added the route another way. This way adds all routes automatically, without having to add one by one.

 

We add the form and the list of comments of a post to the view:

And if we want, we can add the number of comments that one post have in the list of posts:

str_plural function will help us to transform a string to plural according to the number we pass.