Ad

FromRequest Validation For Get Method Is Not Working -Laravel

I am doing request validation using FormRequest Method. I am using GET method. All things seems correct but validation is not working. My Controller

use App\Http\Requests\V1\Admin\Create\SubToTop\TheSubject\UpdateTheSubjectRequest;
use Illuminate\Http\Request;
public function store(TheSubjectStoreRequest $request)
    {
        return 'Hello';
    }

My FormRequest

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'
        ];
    }
Message
 "message": "The given data was invalid.",
    "errors": {
        "subject_code": [
            "Required,Can't Be Empty"
        ]
    }

** I read somewhere FormRequest is not good for GET method.Then How can I validate for GET (except traditional method)

Please Help

Ad

Answer

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);
    }
Ad
source: stackoverflow.com
Ad