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
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
I'm building a REST API with Laravel and wondering if there is a way to customize the API responses when validating.
For example, I have a validation rule in a Laravel request, saying a specific field is required.
public function rules() {
return [
'title'=>'required|min:4|max:100',
];
}
So, for this validation I get the error message in Postman like this
{
"title": [
"Please enter Ad Title"
]
}
What I want is to customize that response like this..
{
"success": false,
"message": "Validation Error"
"title": [
"Please enter Ad Title"
]
}
So, that the error is more specific and clear.
So, how to achieve this ?
Thanks!
I got a solution for your REST-API Validation Laravel FormRequest Validation Response are change by just write a few lines of code.
enter code here
Please add this two-line into your App\Http\Requests\PostRequest.php
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
after that add this function in your file.
you can change $response variable into your specific manner.
protected function failedValidation(Validator $validator) {
$response = [
'status' => false,
'message' => $validator->errors()->first(),
'data' => $validator->errors()
];
throw new HttpResponseException(response()->json($response, 200));
}
Provide a custom function to the FormRequest class called messages and return an array of validation messages mapped using dot notation for specific messages on specific rules:
public function messages()
{
return [
'title.required' => 'Please enter an Ad title',
'title.min' => 'Your title must be at least 4 character'
]
}
Returning a success message is futile as if it fails a 422 error code will be thrown when performing an ajax request anyway.
As for the message property, you will receive that as part of the payload, wherein the actual validation errors will be contained in the object.
You can customize errors, check the documentation. also you can validate in this way
$validator = Validator::make($request->all(), [
'title'=>'required|min:4|max:100'
]);
if ($validator->fails()) {
// get first error message
$error = $validator->errors()->first();
// get all errors
$errors = $validator->errors()->all();
}
then add them to your response, for example
return response()->json([
"success" => false,
"message" => "Validation Error"
"title" => $error // or $errors
]);
In order to reuse code, I created my own validator rule in a file named ValidatorServiceProvider :
class ValidatorServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('checkEmailPresenceAndValidity', function ($attribute, $value, $parameters, $validator) {
$user = User::where('email', $value)->first();
// Email has not been found
if (! $user) {
return false;
}
// Email has not been validated
if (! $user->valid_email) {
return false;
}
return true;
});
}
public function register()
{
//
}
}
And I use this rule like this :
public function rules()
{
return [
'email' => 'bail|required|checkEmailPresenceAndValidity'
];
}
But, I want to set different error messages for each case, something like this :
if (! $user) {
$WHATEVER_INST->error_message = 'email not found';
return false;
}
if (! $user->valid_email) {
$WHATEVER_INST->error_message = 'invalid email';
return false;
}
But I don't figure out how to achieve this without doing 2 different rules ...
Of course it could work with multiple rules but it will also perform multiple SQL queries, and I really want to avoid that.
Also, keep in mind that in real case I could have more than 2 validations like theses in a single rule.
Does anyone have an idea ?
=====
EDIT 1 :
Actually, I think that I want something that works in a similar way to the between or size rules.
They represent one single rule, but provide multiple error messages :
'size' => [
'numeric' => 'The :attribute must be :size.',
'file' => 'The :attribute must be :size kilobytes.',
'string' => 'The :attribute must be :size characters.',
'array' => 'The :attribute must contain :size items.',
],
Laravel checks if the value represents a numeric, a file, a string or an array ; and gets the right error message to use.
How do we achieve this kind of thing with custom rule ?
Unfortunately Laravel doesn't currently provide a concrete way to add and call your validation rule directly from your attribute params array. But that does not exclude a potential and friendly solution based on Trait and Request usage.
Please find below my solution for example.
First thing is to wait for the form to be processed to handle the form request ourselves with an abstract class. What you need to do is to get the current Validator instance and prevent it from doing further validations if there's any relevant error. Otherwise, you'll store the validator instance and call your custom user validation rule function that you'll create later :
<?php
namespace App\Custom\Validation;
use \Illuminate\Foundation\Http\FormRequest;
abstract class MyCustomFormRequest extends FormRequest
{
/** #var \Illuminate\Support\Facades\Validator */
protected $v = null;
protected function getValidatorInstance()
{
return parent::getValidatorInstance()->after(function ($validator) {
if ($validator->errors()->all()) {
// Stop doing further validations
return;
}
$this->v = $validator;
$this->next();
});
}
/**
* Add custom post-validation rules
*/
protected function next()
{
}
}
The next step is to create your Trait which will provide the way to validate your inputs thanks to the current validator instance and handle the correct error message you want to display :
<?php
namespace App\Custom\Validation;
trait CustomUserValidations
{
protected function validateUserEmailValidity($emailField)
{
$email = $this->input($emailField);
$user = \App\User::where('email', $email)->first();
if (! $user) {
return $this->v->errors()->add($emailField, 'Email not found');
}
if (! $user->valid_email) {
return $this->v->errors()->add($emailField, 'Email not valid');
}
// MORE VALIDATION POSSIBLE HERE
// YOU CAN ADD AS MORE AS YOU WANT
// ...
}
}
Finally, do not forget to extend your MyCustomFormRequest. For example, after your php artisan make:request CreateUserRequest, here's the easy way to do so :
<?php
namespace App\Http\Requests;
use App\Custom\Validation\MyCustomFormRequest;
use App\Custom\Validation\CustomUserValidations;
class CreateUserRequest extends MyCustomFormRequest
{
use CustomUserValidations;
/**
* Add custom post-validation rules
*/
public function next()
{
$this->validateUserEmailValidity('email');
}
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'email' => 'bail|required|email|max:255|unique:users',
'password' => 'bail|required',
'name' => 'bail|required|max:255',
'first_name' => 'bail|required|max:255',
];
}
}
I hope that you'll find your way in what I suggest.
If you are using Laravel 8 and would like to display different error messages for a specific validation, follow the steps below.
I am going to create a validation rule that checks if a field is a valid email or a valid phone number. It will also return different error messages.
Make a custom validtion rule like
php artisan make:rule EmailOrPhone
Navigate to the created file in Rules Folder ie Root->App->Rules->EmailOrPhone.php
Paste the following code
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
class EmailOrPhone implements Rule
{
public $error_message;
public function __construct()
{
}
public function passes($attribute, $value)
{
$value = trim($value);
if (is_numeric($value)){
if (strlen($value) != 10){
$this->error_message = "Phone number must contain 10 digits";
return false;
}else if (!Str::startsWith($value, '0')){
$this->error_message = "Phone number must start with 0";
return false;
}else{
return true;
}
}else{
$validator = Validator::make(['email' => $value],[
'email' => 'required|email'
]);
if($validator->passes()){
return true;
}else{
$this->error_message = "Please provide a valid email address";
return false;
}
}
}
public function message()
{
return $this->error_message;
}
}
You can now use the custom validation in your validator like
return Validator::make($data, [
'firstname' => ['required', 'string', 'max:255'],
'lastname' => ['required', 'string', 'max:255'],
'email_phone' => ['required', 'string', 'max:255', new EmailOrPhone()],
'password' => ['required', 'string', 'confirmed'],
]);
Poor handling of custom validation rules is why I ditched laravel (well, it was one of many reasons, but it was the straw that broke the camel's back, so to speak). But anyway, I have a three part answer for you: a reason why you don't want to do this in this specific case, a quick general overview of the mess you have to deal with, and then the answer to your question in case you still want to do it.
Important security concern
Best security practices for managing logins dictate that you should always return one generic error message for login problems. The quintessential counter-example would be if you returned "That email is not registered with our system" for an email-not-found and "Wrong password" for a correct email with the wrong password. In the case where you give separate validation messages, you give potential attackers additional information about how to more effectively direct their attacks. As a result, all login-related issues should return a generic validation message, regardless of the underlying cause, something to the effect of "Invalid email/password combination". The same is true for password recovery forms, which often say something like, "Password recovery instructions have been sent to that email, if it is present in our system". Otherwise you give attackers (and others) a way to know what email addresses are registered with your system, and that can expose additional attack vectors. So in this particular case, one validation message is what you want.
The trouble with laravel
The issue you are running into is that laravel validators simply return true or false to denote whether or not the rule is met. Error messages are handled separately. You specifically cannot specify the validator error message from inside your validator logic. I know. It's ridiculous, and poorly planned. All you can do is return true or false. You don't have access to anything else to help you, so your pseudo code isn't going to do it.
The (ugly) answer
The simplest way to create your own validation messages is to create your own validator. That looks something like this (inside your controller):
$validator = Validator::make($input, $rules, $messages);
You would still have to create your validator on boot (your Valiator::Extend call. Then you can specify the $rules normally by passing them in to your custom validator. Finally, you can specify your messages. Something like this, overall (inside your controller):
public function login( Request $request )
{
$rules = [
'email' => 'bail|required|checkEmailPresenceAndValidity'
]
$messages = [
'checkEmailPresenceAndValidity' => 'Invalid email.',
];
$validator = Validator::make($request->all(), $rules, $messages);
}
(I don't remember if you have to specify each rule in your $messages array. I don't think so). Of course, even this isn't very awesome, because what you pass for $messages is simply an array of strings (and that is all it is allowed to be). As a result, you still can't have this error message easily change according to user input. This all happens before your validator runs too. Your goal is to have the validation message change depending on the validation results, however laravel forces you to build the messages first. As a result, to really do what you want to do, you have to adjust the actual flow of the system, which isn't very awesome.
A solution would be to have a method in your controller that calculates whether or not your custom validation rule is met. It would do this before you make your validator so that you can send an appropriate message to the validator you build. Then, when you create the validation rule, you can also bind it to the results of your validation calculator, so long as you move your rule definition inside of your controller. You just have to make sure and not accidentally call things out of order. You also have to keep in mind that this requires moving your validation logic outside of the validators, which is fairly hacky. Unfortunately, I'm 95% sure there really isn't any other way to do this.
I've got some example code below. It definitely has some draw backs: your rule is no longer global (it is defined in the controller), the validation logic moves out of the validator (which violates the principle of least astonishment), and you will have to come up with an in-object caching scheme (which isn't hard) to make sure you don't execute your query twice, since the validation logic is called twice. To reiterate, it is definitely hacky, but I'm fairly certain that this is the only way to do what you want to do with laravel. There might be better ways to organize this, but this should at least give you an idea of what you need to make happen.
<?php
namespace App\Http\Controllers;
use User;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class LoginController extends Controller
{
public function __construct() {
Validator::extend('checkEmailPresenceAndValidity', function ($attribute, $value, $parameters, $validator) {
return $this->checkLogin( $value ) === true ? true : false;
});
}
public function checkLogin( $email ) {
$user = User::where('email', $email)->first();
// Email has not been found
if (! $user) {
return 'not found';
}
// Email has not been validated
if (! $user->valid_email) {
return 'invalid';
}
return true;
}
public function login( Request $request ) {
$rules = [
'email' => 'bail|required|checkEmailPresenceAndValidity'
]
$hasError = $this->checkLogin( $request->email );
if ( $hasError === 'not found' )
$message = "That email wasn't found";
elseif ( $hasError === 'invalid' )
$message = "That is an invalid email";
else
$message = "Something was wrong with your request";
$messages = [
'checkEmailPresenceAndValidity' => $message,
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
// do something and redirect/exit
}
// process successful form here
}
}
Also, it is worth a quick note that this implementation relies on $this support for closures, which (I believe) was added in PHP 5.4. If you are on an old version of PHP you'll have to provide $this to the closure with use.
Edit to rant
What it really boils down to is that the laravel validation system is designed to be very granular. Each validation rule is specifically only supposed to validate one thing. As a result, the validation message for a given validator should never have to be changed, hence why $messages (when you build your own validator) only accepts plain strings.
In general granularity is a good thing in application design, and something that proper implementation of SOLID principles strive for. However, this particular implementation drives me crazy. My general programming philosophy is that a good implementation should make the most common uses-cases very easy, and then get out of your way for the less-common use-cases. In this cases the architecture of laravel makes the most common use-cases easy but the less common use-cases almost impossible. I'm not okay with that trade off. My general impression of Laravel was that it works great as long as you need to do things the laravel way, but if you have to step out of the box for any reason it is going to actively make your life more difficult. In your case the best answer is to probably just step right back inside that box, i.e. make two validators even if it means making a redundant query. The actual impact on your application performance likely will not matter at all, but the hit you will take to your long-term maintainability to get laravel to behave the way you want it will be quite large.
Alternatively to the other proposals, I think you could also call Validator::replacer('yourRule', function()) in addition to Validator::extend('yourRule', function(...)) and keep track of what causes validation failures in the service provider class you're extending the validator from. This way, you are be able to completely replace the default error message with another one.
According to docs, replacer() is meant for making placeholder replacements in the error message before it is being returned, so while this is not strictly that case, it is close enough. Of course, it's kind of an ugly(ish) workaround, but it will probably work (at least it seems to work for me, at a first glance).
One thing to keep in mind though is that you'll probably have to keep track of these failure causes in an array if you want to avoid automatically returning same message for all fields that failed your custom validation rule.
Where have you found the error messages for the size validation?
I looked up the validation rules in the
Illuminate\Validation\ConcernsValidatesAttributes trait and all functions return a bool value (also the size validation).
protected function validateSize($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'size');
return $this->getSize($attribute, $value) == $parameters[0];
}
What you have found belongs to this part:
$keys = ["{$attribute}.{$lowerRule}", $lowerRule];
In this case it's only for formatting the the output by setting a lowerRule value, that laravel handles in special cases, like the size validation:
// If the rule being validated is a "size" rule, we will need to gather the
// specific error message for the type of attribute being validated such
// as a number, file or string which all have different message types.
elseif (in_array($rule, $this->sizeRules)) {
return $this->getSizeMessage($attribute, $rule);
}
So as long as validation rules have to return a bool value there is no way to return more than one error message. Otherwise you have to rewrite some party of the validation rules.
An approach for your problem with the validation you could use the exists validation:
public function rules()
{
return [
'email' => ['bail', 'required', Rule::exists('users')->where(function($query) {
return $query->where('valid_email', 1);
})]
];
}
So you would need 2 exists validation rules. I would suggest to use the existing one from laravel to check if the email is set and a custom one to check if the account is validated.
In my AppServideProvider's boot method I've set a custom validation rule for cyrillic. Here is what it lookes like:
public function boot()
{
Validator::extend('cyrillic', function ($attribute, $value, $parameters, $validator) {
return preg_match('/[А-Яа-яЁё]/u', $value);
});
}
It works as expected. However if the validation doesn't pass because of latin input I get the error message 'validation.cyrillic'. How can I fix that? How can I pass a custom message to my 'cyrillic' validation rule?
If you want to define it globally, you need to edit the validation file or files, which is/are located in resources/lang/LANG/validation.php where LANG is whatever language you want to define is.
For instance, for the English ones, open the file resources/lang/en/validation.php and add your message like below.
return [
'accepted' => 'The :attribute must be accepted.',
'active_url' => 'The :attribute is not a valid URL.',
// Add yours to somewhere in the first level of the array
'cyrillic' => 'The :attribute is not Cyrillic.'
]
For locally, you can define it within a Request.
public function messages()
{
return [
'cyrillic' => 'The :attribute is not Cyrillic.'
];
}