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.

php artisan make:request ArticleRequest
 

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

<?php
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ArticleRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

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,

<?php

namespace App\Http\Requests;

use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

use Illuminate\Foundation\Http\FormRequest;

class ArticleRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required',
            'body' => 'required',
        ];
    }

    /**
     * Get the error messages that apply to the request parameters.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'title.required' => 'Title field is required',
            'body.required' => 'Body field is required',
        ];
    }
    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        $errors = (new ValidationException($validator))->errors();
        throw new HttpResponseException(response()->json(['errors' => $errors
        ], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
    }
}

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,

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\ArticleRequest;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  use Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(ArticleRequest $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  use Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ArticleRequest $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

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.


share :

Sagar Gautam

A Computer Engineer from Nepal.


Leave your Feedback