Laravel 5.4 #4 : Insert data from a form and validate it

In this post, we will try to insert data from a form through the POST method and then validate if this data is correct.

Insert data from a from

First of all, we define the fields that will be fillable in the model, adding the following line to the model:

We are going to add the new route that will be POST type, which is a type of HTTP method that passes parameters in a way that aren’t visible, not as by GET passing them by URL.

Then, we open the file of the routes and add at the end this:

Now go to the controller and add this:

What it does is to take the data passed through POST through the $request variable and insert it through the create method of the Post model that refers to the posts table of the database. Then simply redirect to the list of posts.

Visiting this link you can find more information about Eloquent ORM and its methods (update to edit, delete to remove, etc.). In other post, we will touch this.

Now only need to add the form to enter the data, I added it to the beginning of the file of the list of posts:

Once we get this done, we have:

 

Validate the data

Following the Laravel documentation about the validations, we will add this code in the controller:

This will validate the POST variable title and body. Title is required, unique y maximum 255 characters. Body will be just required.

But only with this code, we won’t be shown the errors in the view. To be shown we have to add this code before the form:

The errors will be in English, to change it, you will have to download the translation of Laravel or do it by yourself and put the files in resources/lang .

 

Validate the data with Form Requests

We will validate the data in a different way, a bit more complex, but in the end does the same. These types of validations are for more complex cases.

Create the file with artisan:

We have created a file in  app/Http/Requests/PostRequest.php , open it and edit the rules and authorize methods:

In the authorize method, we can add if you can send data according to your role, permissions, if owner, etc..

To apply this new way, we go to the controller and modify the method where the previous validation is:

 

And once we get this done, the result will be the same as the other one.

 

In the next post, we go deeper into Blade, Laravel’s template engine.

 

-

Validations: https://laravel.com/docs/5.4/eloquent