laravel how to validate from custom request object? - php

I'm trying to validate a request like this.
public function reply(CustomRequest $request)
{
$request->validated();
}
The issue is that it will automatically redirect to the previous page if the validation fails. Whereas I want to do some custom logic.
For example
if($request->validation->fails()) {
// Do things
}
But I can't find a way to do this without passing in validation rules, whereas I want to use the rules from the "CustomRequest" class.

Using the Validator::make(), you can redirect your customised stuff.
Here is an example how you can return the first error in the ErrorBag:
$validator = Validator::make($request->all(), [
'field' => ['required']
]);
if ($validator->fails()) {
return redirect()->back()->with('custom_error', $validator->errors()->first());
};

Related

Control where a redirect goes after failed validation

Is it possible to set the redirect path should a request fail validation in Laravel 7? Example:
public function handleForm(Request $request)
{
if (! $request->validate(['someData' => 'required|size:12|alpha_num'])) {
return redirect(...);
}
}
In this particular case, if someData doesn't validate, Laravel redirects me to the path the request originally came from. This is not the behavior I want to see. I would like to be able to define a different path to redirect to. Is that possible?
Use Laravel Validation's fails() method to check if it fails, then redirect on which route you desired.
$validator = Validator::make($request->all(), [
'someData' => 'required|size:12|alpha_num',
]);
if ($validator->fails()) {
return redirect(...);
}
documentation

Laravel, Handling validation errors in the Controller

So i'm working on validating a form's inputs using the following code:
$request->validate([
'title' => 'bail|required|max:255',
'body' => 'required',
]);
So basically, there are two fields in the form, a title and a body and they have the above rules. Now if the validation fails I want to catch the error directly in the controller and before being redirected to the view so that I can send the error message as a response for the Post request. What would be the best way to do it?
I understand that errors are pushed to the session but that's for the view to deal with, but i want to deal with such errors in the controller itself.
Thanks
If you have a look at the official documentation you will see that you can handle the input validation in different ways.
In your case, the best solution is to create the validator manually so you can set your own logic inside the controller.
If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade.
Here a little example:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'bail|required|max:255',
'body' => 'required',
]);
// Check validation failure
if ($validator->fails()) {
// [...]
}
// Check validation success
if ($validator->passes()) {
// [...]
}
// Retrieve errors message bag
$errors = $validator->errors();
}
For someone who wants to know how to get validation errors after page redirection in the controller:
$errors = session()->get('errors');
if ($errors) {
//Check and get the first error of the field "title"
if ($errors->has('title')) {
$titleError = $errors->first('title');
}
//Check and get the first error of the field "body"
if ($errors->has('body')) {
$bodyError = $errors->first('body');
}
}
$errors will contain an instance of Illuminate/Contracts/Support/MessageBag
You can read more on the API here: https://laravel.com/api/8.x/Illuminate/Contracts/Support/MessageBag.html
Note: I have tested it in Laravel 8, it should work on Laravel 6+ if you get the MessageBag from the session

Getting the ErrorMessage Bag in Laravel Validation during Validation

As the question states. I am using the validation method where the Rules and Custom Messages are placed in the Http/Requests folder. However, I want to get the messageErrorBag in Laravel I don't have any problems if I am using the code below I can easily add my own variables to be passed together with the validator message bag.
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
However, if using the code below. I cannot do it since Laravel already handles the error return as per documentation.
public function store(StoreBlogPost $request)
{
// The incoming request is valid...
// Retrieve the validated input data...
$validated = $request->validated();
}
My question how can I do it? before it redirects back with the error message bag.? Is it possible
If you use StoreBlogPost in Controller , it automatically returns messages but if you want your messages in body of controller you should add validator to your controller body and use this code:
if ($validator->fails())
{
foreach ($validator->messages()->getMessages() as $field_name => $messages)
{
var_dump($messages); // messages are retrieved (publicly)
}
}
hope it helps

Api validation in laravel 5.4

Hi guys I'm working on API but I need to validate some data at backend, in this case, we only need a postman to send parameters and headers.
All is working fine now but I need more useful data in each request, Laravel has by default a Validator Form Request Validation, but I donĀ“t know how to use at API side.
I need to send the error message in JSON to Postman.
I found two options, one, make validations into a controller but seems to much code and the other make a php artisan make:request StoreObjectPost and then import the request into the controller and change the request of the store method, which one do you recommend, Ty!
You could instantiate the validator yourself like this:
$validator = Validator::make($request->all(), [
'name' => 'min:5'
]);
// then, if it fails, return the error messages in JSON format
if ($validator->fails()) {
return response()->json($validator->messages(), 200);
}
$PostData = Input::all();
$Validator = Validator::make(array(
'name' => $PostData['name']
), array(
'name' => 'required'
));
if ($Validator->fails()) { //if validator is failed
return false;
} else {
// do some thing here
}
Hope this may help you
You should override response(array $errors) method of FormRequest.
public function response(array $errors)
{
//Format your error message
if ($this->expectsJson()) {
return new JsonResponse($errors, 422);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
I prefer the second option. We will be able to keep our controller clean that way, even when we use many validations for the data or using custom error message in the validation

Laravel request validator redirect with errors

I would like to make a validator through the usage of Laravel requests, and validation is working fine. But if I don't do them in the controller I can't return back to view with errors if validator fails.
Is it possible to implement this:
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
within the custom request? Something like this maybe:
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
]; // ->withErrors()
}
FormRequest by default returns the user back to the previous page with the errors and input. You don't have to specify it manually. Just set the rules and use the newly created FormRequest in your controller method instead of using the Request object.
This is what happens under the hood.
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);

Categories