Laravel Active Validation Rule - laravel

I am extremely new to Laravel and I was wondering if you could help me create a Custom Validation Rule, I am using version 5.5 of Laravel.
What I try to do is the following, I understand that the validations can be defined in the following way:
'email' => 'required|string'
I would like to add a new rule, in specific one called 'active'
In the application that I want to create I have several tables in which there are columns called 'active' (boolean) .. example
Users:
id|name|email|active
Roles:
id|name|active
I need a rule that I can call as follows:
'email' => 'required|string|active'
In short, I need a rule that verifies in a specific table, if the value I'm validating is active, and if not, send me a message. Thank you very much in advance

Try to use the Rule class and 'exists' validation:
use Illuminate\Validation\Rule;
'email' => [
'required',
'string',
Rule::exists('your_table')->where(function ($query) {
$query->where('active', 1);
}),
]

Related

Required if in laravel nova field

I have got 2 fields in nova that one needs to be required if he chooses 'Business' for example.
Date::make('Payment till', 'payed_until')
->default(function ($request) {
return '2035-01-01';
})
->rules('required','date')
,
Select::make('Role', 'role')->options([
'Client' => 'Client',
'Business' => 'Business',
'Admin' => 'Admin',
])->rules('required')->canSeeWhen('edit-user-roles'),
so I tried to make it only when Business role has been choose only then the Payed until will be required. but I couldn't make it work.
I tried required_if inside with function, which gave me an error.
Thanks in advance.

Laravel validations

I want to validate my backend code with the following data.I passed date as $request->get('date_from'),$request->get('date_to') and time as $request->get('time_from'), $request->get('time_to') from my angular frontend and I convert date time as follows.
$dateTime_from=date('Y-m-d',strtotime($request->get('date_from'))).' '.$request->get('time_from');
$dateTime_to=date('Y-m-d',strtotime($request->get('date_to'))).' '.$request->get('time_to');
Now I want to validate DateTime with laravel backend validations. dateTime_from should be less than dateTime_to.How can write down that code inside validator?
$this->validate($request, [
'vehicle_id'=>'required',
'time_to'=>'required',
'event_id'=>'required',
]);
You can use the after validation rule.
$this->validate($request, [
'vehicle_id' => 'required',
'date_to' => 'required|after:date_from',
'event_id' => 'required'
]);
https://laravel.com/docs/5.8/validation#rule-after
you can use the after rule like follows
'date_to' => 'required|date|after:date_from'
Instead of passing a date string to be evaluated by strtotime, you may specify another field to compare against the date:
Also, you have rule-before as well
EDIT
I think after rule takes the time into consideration as well, but not sure.
And you have really complex validation to do, better write a custom rule class or a closure to handle it for you
'date_to' => [ 'required',
'date',
function ($attribute, $value, $fail) {
if (strtotime($value) <= strtotime($request->date_from) {
$fail(':attribute needs to be higher than date_from!'); // or whatever mesage ou need to send
}
]

Laravel validation for accepting only predefined values from api

Basically I wrote an api in laravel, The api should return a validation error if any of the key has wrong values (spelling mistakes,extra space). To make more clarity, in the web interface these key values are from select boxes . so users do not get to type anything.
First consider using in_array function for every inputs. I think that works. But i would like to know if there is anything for laravel specific.
something like
'email' => 'required | email| 'sandy#stackoverflow.com'
to make it ease. I could not find it unfortunately. It seems not that hard.
I believe you can achieve this with in, for example:
$rule = [
'email' => 'in:sandy#stackoverflow.com',
];
Or you could try it including the Rule namespace as described in the docs here
use Illuminate\Validation\Rule;
Validator::make($data, [
'zones' => [
'required',
Rule::in(['first-zone', 'second-zone']),
],
]);

Adding validation rule only if all other rules pass, or stop validating entire set of attributes on the first error in Laravel 5.7

I want to allow a user to create a folder on the local storage disk. So the form that is sent to the server quite is simple and has three attributes:
new-folder-name - that is the name of the folder to be created,
relative-path - a path to the directory inside which the new directory should be created relative to an asset root directory, and
asset_id - the id of an asset, I need this id to get the asset's root directory.
The thing is when I validate these attributes I need to also check if the folder the user is going to create already exists. For this purpose I made a rule called FolderExists. So, before I run FolderExists, I have to be sure all other rules have passed successfully because my custom rule should accept relative-path and asset_id to be able to build the path to check against.
Here is my rules() function, I'm doing validation in custom form request:
public function rules()
{
return [
'asset_id' => ['bail', 'required', 'exists:assets,id'],
'relative-path' => ['bail', 'required', 'string'],
'new-folder-name' => ['bail', 'required', 'string', 'min:3', new FolderName, new FolderExists($this->input('asset_id'), $this->input('relative-path')]
];
}
So my question is:
Is it possible to add FolderExists only if all other validation rules pass?
Or maybe it's possible to stop entire validation when the validator encounters first error?
Both options should be fine here.
Thank you!
I have finally found the solution myself. Here is what I ended up with.
To achieve the desired result I created another validator in withValidator() method of my custom form request, this second validator will handle only the FolderExists rule and only if the previous validation fails.
public function rules()
{
return [
'asset-id' => ['bail', 'required', 'integer', 'exists:assets,id'],
'relative-path' => ['bail', 'required', 'string'],
'new-folder-name' => ['bail', 'required', 'string', 'min:3', 'max:150', new FolderName]
];
}
public function withValidator($validator)
{
if (!$validator->fails())
{
$v = Validator::make($this->input(),[
'new-folder-name' => [new FolderExists($this->input('asset-id'), $this->input('relative-path'))]
]);
$v->validate();
}
}
If our main validator passes, we make another validator and pass only FolderExists rule with its arguments, that have already been validated, and call validate() method. That's it.

How to allow empty value for Laravel numeric validation

How to set not require numeric validation for Laravel5.2? I just used this Code but when i don't send value or select box haven't selected item I have error the val field most be numeric... I need if request hasn't bed input leave bed alone. leave bed validate ...
$this->validate($request, [
'provinces_id' => 'required|numeric',
'type' => 'required',
'bed' => 'numeric',
]);
If I understood you correctly, you're looking for sometimes rule:
'bed' => 'sometimes|numeric',
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list
In Laravel 6 or 5.8, you should use nullable. But sometimes keyword doesn't work on that versions.
Use sometimes instead of required in validation rules. It checks if only there is a value. Otherwise it treats parameter as optional.
You may need nullable – sometimes and
present didn't work for me when combined with integer|min:0 on a standard text input type - the integer error was always triggered.
A Note on Optional Fields
By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. Because of this, you will often need to mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid.
Tested with Laravel 6.0-dev
Full list of available rules
In laravel 5.5 or versions after it, we begin to use nullable instead of sometimes.
according to laravel documentation 8 you must to set nullable rule
for example:
$validated = $request->validate([
'firstName' => ['required','max:255'],
'lastName' => ['required','max:255'],
'branches' => ['required'],
'services' => ['required' , 'json'],
'contract' => ['required' , 'max:255'],
'FixSalary' => ['nullable','numeric' , 'max:90000000'],
'Percent' => ['nullable','numeric' , 'max:100'],
]);
in your case :
$this->validate($request, [
'provinces_id' => 'required|numeric',
'type' => 'required',
'bed' => 'nullable|numeric',
]);

Resources