Search code examples
laravelmiddleware

In a Laravel REST application, is it correct to use middleware to verify the input?


Having a Laravel application that is offering a REST service

In every call to the service I expect some parameters, requests are going to be routed and passed to a Controller.

Is it correct to implement some middleware to check on requests correctness or there's some case (don't know yet which ones) where it is better to implement input validation inside the controller?

Thinking to Laravel 4 Filters, that have been move to Middleware solution, I would go for placing the input validation logic inside a middleware instance.


Solution

  • You should be using FormRequest and a controller that uses ValidatesRequests.

    In doing so, you can specify validation and authorization rules for every individual request.

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Http\Requests\SomeFormRequest;
    use Illuminate\Foundation\Validation\ValidatesRequests;
    use Illuminate\Routing\Controller as BaseController;
    
    class SomeController extends BaseController
    {
       use ValidatesRequests;
    
       /**
        * Store the incoming blog post.
        *
        * @param  SomeFormRequest  $request
        * @return Response
        */
        public function store(SomeFormRequest $request)
        {
            // The incoming request has already been validated
        }
    }
    

    Here, you can delegate validation to another class, and always make the assumption that if the controller method is being called, then the validation passed.