Reputation: 427
I wanted to validate inputs from a GET request without using the
this->validate($request... or \Validator::make($request...
and prefer to do it like
$input = $request->validate([... rules ...]);
however since get requests doesn't have $request parameters how can I achieve it?
public function sampleGet($param1, $param2) {
// How can I pass the $param1 and $param to to validate?
$input = $request->validate([
'param1' => 'required',
'param2' => 'required
]);
}
Upvotes: 5
Views: 17284
Reputation: 101
You can use Validator class
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
$request = Request::capture();
$validator = Validator::make($request->query(), [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users|max:255',
]);
if ($validator->fails()) {
// Do something with the failed validation
dd("test");
}
Upvotes: 1
Reputation: 302
You can do like that.
public function getData(Request $request)
{
try {
$input['route1'] = $request->route('route1');
$input['route2'] = $request->route('route2');
$valid = Validator::make($input, [
'route1' => 'required',
'route2' => 'required'
]);
} catch (\Throwable $th) {
echo "<pre>";print_r($th->__toString());die;
}
}
Or you can follow the below link for more info.
https://laravel.com/docs/7.x/validation#manually-creating-validators
Upvotes: 0
Reputation: 50491
If you want all the route parameters you can get them as an array:
$request->route()->parameters()
Since you already have those parameters being passed to your method you can just build an array with them:
compact('param1', 'param2');
// or
['param1' => $param1, 'param2' => $param2];
You are not going to be using the validate
method on the Request though, you will have to manually create a validator. Unless you want to merge this array into the request or create a new request with these as inputs.
There is nothing special about the validate
method on a Controller or on a Request. They are all making a validator and validating the data the same way you would yourself.
When manually creating a validator you still have a validate
method that will throw an exception, which would be the equivalent to what is happening on Request and the Controller with their validate
methods.
Laravel 7.x Docs - Validation - Manualy Creating Validators - Automatic Redirection
Upvotes: 3
Reputation: 2545
You can do so and it will have same behavior as validate
validator($request->route()->parameters(), [
'param1' => 'required',
'param2' => 'required'
....
])->validate();
Upvotes: 3