'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
Solution 1:[1]
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);
}
Solution 2:[2]
To define some validation rules on GET method parameters, you can use ->where('A' => '[0-9]+') at the end of your Route definition on web.php page
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Saber Fazliahmadi |