i have example object with fields
name => John
surname => Dow
job => engineer
and output form with placeholders. some required, some not.
what is best practice for check if it requred and show error with null fields?
There are multiple ways actually you can do that inside of controller method or make use of Laravels Request Classes for me I prefer to use Request Classes
look below I will list the two examples
Validate inside the controller's method
public function test(Request $request){
if($request->filled('name){
/*filled will check that name is set on the current
request and not empty*/
//Do your logic here
}
}
Second way is by using the Validator Facade inside your controller
use Validator;
class TestController{
public function test(Request $request){
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
/*continue with your logic here if the request failed on
validator test Laravel will automatically redirect back
with errors*/
}
}
Third way my favorite one personally
you can generate a Request class using this command
php artisan make:request AddBookRequest
that will generate the request class under "app/Http/Requests/AddBookRequest" , inside of any generated request class you will find two methods authorize() and rules()
in the authorized method you have to return truthy or falsy value this will detect if the current user making the request has authorization to fire this request inside of the rules method you do pretty much as you did in the Validator in the second way check the example
public function authorize(){
return true;
}
public function rules(){
return [
'title' => 'required|string',
'author_id' => 'required|integer'
];
}
then simply in your controller you can use the generated request like this
use App\Http\Requests\AddBookRequest;
public function store(AddBookRequest $request){
/* do your logic here since we uses a request class if it fails
then redirect back with errors will be automatically returned*/
}
Hope this helps you can read more about validation at
https://laravel.com/docs/5.6/validation
I think "simple is the best", just through object and check if properties exists
Ref: property_exists
Example:
if (property_exists($object, 'name')) {
//...do something for exists property
} else {
//...else
}
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.
I am pretty new in Laravel and I have the following problem.
I have to declare a route that handle requests like this:
http://laravel.dev/activate?email=myemail#gmail.com&token=eb0d89ba7a277621d7f1adf4c7803ebc
So this URL have to mantein this format (activate as resource and 2 query parameters in the form ?email and &token. This is not a REST URI. I need to use it in this way).
I need a route and a controller method that handle this kind of request.
I know that I can do something like this:
1) Into the routes/web.php file I declare a rout like this
Route::get('/activate','MyController#myMethod');
2) Into MyController I declare this method:
public function myMethod(Request $request) {
if(Input::has('email') && Input::has('token')) {
$email = $request->input('email');
$token= $request->input('token');
// DO SOMETHING USING $email AND $token
}
else {
// SHOW ERROR PAGE
}
}
But onestly I find it pretty horrible. I came from Java and using Spring framework I can specify in the mapping between the URL and the controller method that a method handle a request toward a resource and that to be handled some specific query paramer have to be passed. Otherwise (if these parameter are not present the HTTP GET request is not handled by the controller method).
I know that in Laravel I can do something like this using REST form of my URL, I think something like this:
For the route mapping:
Route::get('/activate/{email}/{token}', [ 'uses' => 'ActivationController#activate', 'as' => 'activate' ]);
And then the controller method will be something like this:
public function activate($email, $token) {
// $email would be 'myemail#gmail.com'
// $token would be 'eb0d89ba7a277621d7f1adf4c7803ebc'
// do stuff...
}
But I can't use this kind of URI in this case (as specified the URL pattern have to be in the format:
http://laravel.dev/activate?email=myemail#gmail.com&token=eb0d89ba7a277621d7f1adf4c7803ebc
So I desire do something like this with this kind of URI. I don't wont to pass the Request $request object to my controller method and then extract the parameters from it but I want to have a controller method signature like this:
public function activate($email, $token) {
in which if all the expected parameters are not passed simply the request will not handled by this controller.
I prefer do it because for me is a neater approach (reading the controller signature another developer immediately know that this method is expecting).
And also because I want that malformed parameters are not handled by the method (so I can avoid to handle error cases like: the user not pass the 2 parameters).
How can I do something like this in Laravel? (if it is possible...)
This is certainly a strange request, because it defies a more traditional use of Laravel routing practices, but this should work for you:
In routes.php (Laravel < 5.3) or web.php (Laravel 5.4+):
Route::get('/activate', [ 'as' => 'activate', function()
{
return app()->make(App\Http\Controllers\ActivateController::class)->callAction('activate', $parameters = [ 'email' => request()->email, 'token' => request()->token ]);
}]);
So we are instantiating the ActivateController class and calling the method 'activate' which is the first argument, then supplying a list of parameters the method receives in the form of an array.
public function activate($email, $token)
{
echo "Email: $email"; // myemail#gmail.com
echo "Token: $token"; // eb0d89ba7a277621d7f1adf4c7803ebc
// do stuff
}
Now, provided you go to http://laravel.dev/activate?email=myemail#gmail.com&token=eb0d89ba7a277621d7f1adf4c7803ebc $email and $token will be the respective key query parameters.
Now, as for validating to ensure that data is present. You have to add another argument to your activate() method, unless you want to do it inline.
The best practice way:
Run php artisan make:request ActivateRequest
A new file called ActivateRequest will be created in app\Http\Requests. Open it up and make sure your authorize() method returns true like so:
public function authorize()
{
return true;
}
Next, in the rules() method there is an array. Add the following:
return [
'email' => 'required|email',
'token' => 'required',
];
If you want to supply your own validation messages to these rules, add a method below rules() called messages() Like so:
public function messages()
{
return [
'email.required' => 'You must supply an email address.',
'email.email' => 'That email is address is not valid.',
'token.required' => 'Please supply a token.',
];
}
Then, back in ActivateController pull in your new FormRequest class at the top use App\Http\Requests\ActivateRequest; and use it in the method like so:
activate($email, $token, ActivateRequest $request) {
...
Now, your request will be validated and you don't even have to use the $request variable.
The inline (not so best practice way)
If you are dead set on not having an extra argument in your method, you can validate data in the controller like so:
First, bring in the Validator class at the top. use Validator;.
public function activate($email, $token)
{
$validationMessages = [
'email.required' => 'You must supply an email address.',
'email.email' => 'That email is address is not valid.',
'token.required' => 'Please supply a token.',
];
$validation = Validator::make(request()->toArray(), [
'email.required' => 'You must supply an email address.',
'email.email' => 'That email is address is not valid.',
'token.required' => 'Please supply a token.',
], $validationMessages);
if ( $validation->fails() )
{
return 'Sorry, there was a problem with your request';
}
// do stuff
}
Hope this helps.
I'm learning Laravel 5 and trying to validate if an email exists in database yet then add some custom message if it fails. I found the After Validation Hook in Laravel's documentation
$validator = Validator::make(...);
$validator->after(function($validator) use ($email) {
if (emailExist($email)) {
$validator->errors()->add('email', 'This email has been used!');
}
});
if ($validator->fails()) {
return redirect('somewhere')
->withErrors($validator);
}
but I don't really understand what this is. Because I can simply do this:
//as above
if (emailExist($email)) {
$validator->errors()->add('email', 'This email has been used!');
}
//redirect as above
It still outputs the same result. When should I use the 1st one to validate something instead of the 2nd one?
The point of the first method is just to keep everything contained inside of that Validator object to make it more reusable.
Yes, in your case it does the exact same thing. But imagine if you wanted to validate multiple items.
foreach ($inputs as $input) {
$validator->setData($input);
if ($validator->fails()) { ... }
}
In your case you will have to add that "if" check into the loop. Now imagine having to run this validation in many different places (multiple controllers, maybe a console script). Now you have this if statement in 3 different files, and next time you go to modify it you have 3x the amount of work, and maybe you forget to change it in one place...
I can't think of many use cases for this but that is the basic idea behind it.
By the way there is a validation rule called exists that will probably handle your emailExist() method
$rules = [
'email' => 'exists:users,email',
];
http://laravel.com/docs/5.1/validation#rule-exists
There may be many scenarios where you may feel it's requirement.
Just assume that you are trying to build REST api for a project. And you have decided that update request method will not have any required rule validation for any field in request (as there maybe many parameters and you do not want to pass them all just to change one column or maybe you do not have all the columns because you aren't allowed access to it) .
So how will you handle this validation in UpdatePostRequest.php class where you have put all the validation rules in rules() method as given in code.
Further more there may be requirement that sum of values of two or more request fields should be greater or less than some threshold quantity. Then what?
I agree that you can just check it in controller and redirect it from there but wouldn't it defeat the purpose of creating a dedicated request class if we were to do these checks in controllers.
What I feel is controllers should be clean and should not have multiple exit points based on validation. These small validation checks can be handled in request class itself by creating a new Rule or extending your own custom validation or creating after validation hooks and all of them have their unique usage in Laravel.
Therefore what you may want to to do here is create a validation hook where it's assigned is to check whether request is empty or not like the example given below
public function withValidator($validator)
{
$validator->after(function ($validator) {
if (empty($this->toArray())) {
$validator->errors()->add('body', 'Request body cannot be empty');
}
if (!$this->validateCaptcha()) {
$validator->errors()->add('g-recaptcha-response', 'invalid');
}
});
}
And here is the full example for it.
<?php
namespace App\Http\Requests\Posts;
use App\Helpers\General\Tables;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdatePostRequest extends FormRequest
{
public function authorize()
{
return auth()->user()->can('update-post', $this);
}
public function rules()
{
return [
'name' => ['string', 'min:3', 'max:255'],
'email' => ['string', 'email', 'min:3', 'max:255'],
'post_data' => ['string', 'min:3', 'max:255'],
];
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
if (empty($this->toArray())) {
$validator->errors()->add('body', 'Request body cannot be empty');
}
});
}
}
Thanks..
passedValidation method will trigger if the validation passes in FormRequest class. Actually this method is rename of afterValidation method. See: method rename Commit
So you can do like
class RegistrationRequest extends FormRequest
{
/**
* Handle a passed validation attempt.
*
* #return void
*/
protected function passedValidation()
{
$this->merge(
[
'password' => bcrypt($this->password),
]
);
}
}
In Laravel 5, using a form request to act as a validation gate, and given the code below:
Controller
public function decline(Request $request, InviteDeclineRequest $validation, $id)
{
$invite = Invite::find($id);
$invite->status = 'declined';
$invite->save();
}
FormRequest
class InviteDeclineRequest extends Request {
public function rules()
{
return [
# this is referring to the incoming data,
# not the existing data
'status': 'pending',
];
}
}
How can I change the above validation ruleset to say, the incoming input is only valid if the existing record's status is set to 'pending'. I.e don't allow a declined invite unless the existing is pending.
Option 1:
Put this logic in the controller. Maybe the above isn't considered a part of validation, (although I would argue that it is), and so doesn't belong in the FormRequest.
Option 2:
Put the logic in the Authorise method of method of the FormRequest. The only downside to this is that the authorise should be for access control, not data validation.
Option 3:
Extend form request to include a third method that validates existing data as well as incoming data. Slightly painful as I need to make sure it gets called as part of the request cycle.
Option 4:
Add a custom validation rule:
http://laravel.com/docs/5.0/validation#custom-validation-rules
You can add to your custom InviteDeclineRequest class method all to add id to data that will be validated:
public function all()
{
$data = parent::all();
$segments = $this->segments();
$id = intval(end($segments));
if ($id != 0) {
$data['id'] = $id;
}
return $data;
}
and now in rules you can use it:
public function rules()
{
return [
'id' => ['required', 'exists:invites,id,status,pending']
];
}
to make sure record you edit has status pending.