Search code examples
phplaravelvalidationlaravel-formrequest

FromRequest Validation for Get Method is not working -Laravel


I am doing GET request validation using a FormRequest class. The rules seem correct, but validation is not working.

My FormRequest class looks like this:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ShowTheSubjectRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {        
        return [
            'subject_code' => 'required|exists:the_subjects,sub_x',
        ];
    }

    public function messages()
    {
        return [
            'subject_code.required' => 'Required,Can\'t Be Empty',
            'subject_code.exists' => 'Entry does\'t exist with us.Choose Correct'
        ];
    }
{

I always get the following response:

{
    "message": "The given data was invalid.",
    "errors": {
        "subject_code": [
            "Required,Can't Be Empty"
        ]
    }
}

I read somewhere that FormRequest is not good for GET method. How else can I validate for GET requests?


Solution

  • You can't use form validation on GET request because it validates the request body, and GET requests have no body. To validate the query string (the URL part after ?), you need to use a middleware which would abort the request whenever something goes wrong.

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    class ValidateSubjectCode
    {
        public function handle($request, Closure $next)
        {
            $subjectCode = $request->route()->param('subject_code');
    
            //Your validation logic
    
            return $next($request);
        }
    }
    

    Because this validation is probably specific to a controller, you could also define a Closure middleware into your controller __construct

    public function __construct()
        {
            $this->middleware(function ($request, $next) {
                $subjectCode = $request->route()->param('subject_code');
    
                //Your validation logic
    
                return $next($request);
        }