Request Validation – Creating REST API in Laravel (Part III)

Request validation includes validation of the request at server sent from client end. In previous article, we discuss about necessary database structure, eloquent model, resource routes and resource controller for api in laravel. In this article, we will discuss request validation for the store and update of the article. We will create a request class and then add some validation rules and messages. Finally we will use this class in controller function for validation purpose.

Let’s create ArticleRequest class with following command.

Above command will create ArticleRequest class inside app/Requests/ directory. We can see following structure which we will modify later.

Now, we have to authorize the request. In order to authorize, we have to return true from authorize function above. After that we will add some validation rules and error messages in the request class. Our class looks like,

We have made title and body field required for the request. We will use this request in the controller functions store and update. Since store and update functions takes data from request, above class will check for required fields. If validation fails then error messages will be returned.

We can see more details about requests in laravel official documentation

Now, we will use above class in our ArticleController like this,

Hence, we can use the request class in the controller function parameter. When we call the controller function, request is validated with rules in the request class. If request satisfies the rules specified then controller function will be executed. In case of request doesn’t satisfies rules then validation errors will be returned.

You can find all the details in github: https://github.com/sagautam5/laravel-rest-api

In the next article, we will add some logic to the controller function to create rest api with laravel.


sagautam5

sagautam5

Computer Enginner, A Laravel Developer,
http://sagargautam.stacklearning.com

Leave a Reply

Your email address will not be published. Required fields are marked *