Validation check if requested value exists in another table Laravel 9 - laravel

Hello i am trying to make a validation that checks the inserted values if they exist or not in other tables. This is the code i have done now:
$request->validate([
'order_number' => 'required',
'client_id' => 'required,exists:clients',
'description' => 'required',
]);
These values are inserted in a table called order but the client_id is taken from another table called clients and i want to verify if the value of client_id exists in the row id of the table clients

Please check here
Laravel Validation
As mentioned in laravel document you need to specify a column name, because if you don't, it will use the key in the request for the column name, so in your example, it will be the clients table and client_id column but you need to specify the column name in exists rule, it will be something like this:
$request->validate([
'order_number' => 'required',
'client_id' => 'required|exists:clients,id',
'description' => 'required',
]);
Also, you used the wrong syntax for separating rules, after required you need to use a pipe(|) to separate your rules and use multiple validations.

Related

How to use Rule:unique with array of values compared to another column in laravel?

i have a request for array of values and i validate it with the following code
$request->validate([
'doctor_id.*' => ['required'],
'doctor_id' => [Rule::unique('project_orders')->where(function ($query) use ($student) {
$query->where('student_id', $student->id);
})],
]);
but the unique validation doesn't work and the data was inserted to the table with duplication
i want the doctor_id field to be unique with the student_id column, what should be the correct rule?
any help please ?
First you need to do validation on database level, so you will add in your migration
$table->unique(['doctor_id', 'student_id']);
This will make sure that there will be no duplication for same doctor_id and student_id values
Then in your validation layer you will add
$request->validate([
'doctor_id.*' => 'unique:project_orders,doctor_id,NULL,id,student_id,'.$student->id,
]);
You can do the validation like this
$request->validate([
'doctor_id.*' => [ Rule::unique('project_orders', 'doctor_id')->where('student_id', $student->id) ]
]);

Validate a field using another field

I have a dynamic phone number validation rule, and I need 2 values for it: number and country.
The library I'm using to validate the phone number is brick/phonenumber which can include the country code to parse it accurately.
So, my current working approach looks like this:
$request->validate([
'country' => ['required', 'max:2'],
]);
$request->validate([
'number' => ['required', new PhoneNumberValidator($request->input('country')],
]);
Because when I put it like this:
$request->validate([
'country' => ['required', 'max:2'],
'number' => ['required', new PhoneNumberValidator($request->input('country'))],
]);
The number validation runs even if the country is not valid. So I'd like to know if there's a way to have all the validations in one validate() call, so, having the country value validated before calling the number rule (I tried with bail but that stops the validations for 1 attribute, not the rest of attributes in the queue).
You can create a custom rule and validate both inputs at the same time.
You may also want to look at the various validation rules. You might find something helpful.

Laravel Collective - Model binding issue for non eloquent table names

I have a User model that has to have a table named admin_users, which is already stipulated in the model (protected $table = 'admin_users';)
I am using Laravel Collective form as follows:
{!! Form::model($user, ['route' => ['users.update', $user->id], 'method' => 'put']) !!}
My validation as follows:
$rules = array(
'first_name' => 'required',
'last_name' => 'required',
'email' => 'email|max:255|unique:users',
'country_id' => 'required|numeric',
'user_status' => 'required'
);
The only reason I am using Laravel Collective FORM::model for the ease of getting the request input back when validation fails:
(return redirect()->back()->withErrors($validator)->withInput($request->all())
On validation success though I am getting:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'crm.users' doesn't exist (SQL: select count(*) as aggregate from `users` where `email` = jocelyn33#example.com)
The weird thing is that it's not taking the table from User class table.
My question is if there is a way to have FORM::model get admin_users table name rather than users, and if I decide to let go of FORM::model and use FORM::open, would I still be able to get back request inputs of a failed validation?
Your validation rules are defining what table to use for a unique check:
'email' => 'email|max:255|unique:users',
unique:users is telling the unique rule to use the users table.
unique:table,column,except,idColumn -
Laravel Docs 5.6 - Validation - Unique Rule

Laravel 5 - Validation

I am confuse how can I validate a user's username if I am updating it. Here's the scenario, if I click a specific user in list of users page it will redirect into a page which has a form with user's data in the form. Now, I have:
public function updateUser(Request $request){
$this->validate($request, [
'username' => 'required|unique:users',
'name' => 'required|max:255'
]);
}
UPDATE
$this->validate($request, [
'name' => 'unique:roles,name,'.$request->id
]);
I know the part where 'username' => 'required|unique:users' is checking if the username exists in the users table, but what if I dont want to change/update the username, and I just want to update the other field, then it says that the username is already exists. How can I validate it in a right way.
Need help guys. This can also help others for this kind of problem.
Laravel will accept a new parameter for the key of the table. This should be the id of the element you would like to ignore in your query.
something like 'username' => 'required|unique:users,username,'.$request->get('id'),
You will have to pass the id variable in your request when updating.
Laravel documentation: https://laravel.com/docs/5.4/validation#rule-unique
You can also try using the Rule class (search for "Forcing A Unique Rule To Ignore A Given ID"), which was added in Laravel version 5.3.
You can see an example of usage of my answer in the documentation at:
https://laravel.com/docs/5.2/validation#rule-unique (search for "Forcing A Unique Rule To Ignore A Given ID")
Update as per question update:
$this->validate($request, [
'name' => 'required|unique:roles, name,'.$request->id
]);
you want to update profile and at that time you stuck with this error "username is already exists". so my suggestion is just remove the required validation from username if username is not updated then don't send it to server, so you no need to check whether it's exists or not in table and also if want to check particular column you can write like this
public function updateUser(Request $request){
$this->validate($request, [
'username' => 'unique:users,column-name',
'name' => 'required|max:255'
]);
}
in above case if we receive a username then we check it's uniqueness else not
You just need to check if the user exists or not
'username' => 'exists:users'
If the user exists in the database you will update it.
What wrong you are doing is: You are trying to update a user and validating that the username should be unique (this validation should be applied during user creation), that is not correct.
Thanks.
EDIT 1
Generally, username or email is a key column which you should not allow the user to update. Otherwise, this problem will always exist.
EDIT 2
I agree with the actual scenario that we can not assume that the username field will always remain same and the user can not update it. If the user is updating the username then you can try this code.
'username' => 'required|unique:users,username,'.$user->id
If your table uses a primary key column name other than id, you may specify it as the fourth parameter:
'username' => 'required|unique:users,username,'.$user->id.',user_id'

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