How to make conditions on laravel form request - php

I have a question,
I have a Controller and I Have a form request to validate the update.
I want to make conditions for example. If I update an "name" the form request allow change the name but if I didn't make change use the same and don't appear "unique rule" because sometimes I have to change the name, but some times not and the problem is when I haven't to change the name because if I put the same name, I have the message "duplicated" and if I try to update another ID appear "duplicated".
I don't know if you understand but i am trying to be specific.
My rule is the next with a condition.
public function rules()
{
if (Attribute::where('name', '=', Request::get('name'))->count() == 1) {
return [
'name' => 'required'
];
} elseif (Attribute::where('name', '=', Request::get('name'))->count() != 1) {
return [
'name' => 'unique:attributes'
];
}
}
So I compare if name count is ==1 only required but when is !=1 only unique but doesn't work correctly.
Some suggestion?

Based on this Answer,
How validate unique email out of the user that is updating it in Laravel?
You can ignore the current user details and preserve the unique rule while validating the update request in such rule,
As per documentation,
Forcing A Unique Rule To Ignore A Given ID:
Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address. You only want to throw a validation error if the user provides an e-mail address that is already used by a different user. To tell the unique rule to ignore the user's ID, you may pass the ID as the third parameter:
Your rule while updating should look like,
'name' => 'unique:attributes,name,'.$attribute->id
Here, $attribute refers to the attribute being updated.
I hope you will understand.

you can use Rule to check unique
use Illuminate\Validation\Rule;
Rule::unique('table_name')->ignore('id');

Related

lumen validation: rule for value not exists in database

i´m using lumen 5.5 and want to prove that a given value is required, exists in table A and does NOT exist in table B.
while the first two rules can be found in the documentation I´m unable to find a solution for the third.
So this is what I currently use:
$rules = [
'email' => 'required|exists:user,email'
];
Something like this is what I want:
$rules = [
'email' => 'required|exists:user,email|not_exists:blocklist,email'
];
Someone know a simple validation rule for this?
Try this:
$rules = [
'email' => 'required|exists:users|unique:blocklist'
];
Explanation:
With the exists rule we are making it sure that the provided email must exist in your users table under the column email.
With the unique rule we are making it sure that there must not exist a matching email in the blocklist table (under the email column).
In both cases, I didn't specify a column name because the attribute name is the same than the matching column in the database. If you want to customize it just include it after a ,. e.g: required|exists:users,another_column

How to compare user input with the data in the database Laravel

I have an input field and would like to compare the data which got sent with those in my database.
Suppose we have a book with a serial number. Now this customer borrows this book and wants to return it after one week. Then he verifies himself with his membership card and sees a table where his borrowed books are listed. Before he can return the book he has to scan the serial number of this book. This is to compare whether the serial number is really in the database.
And this is exactly what I'm looking for help with, everything else I've implemented so far, and with the help of this community I'd like to thank everyone again.
Now I need your help again how I could implement this check. I think I could solve it somehow in the controller with an if statement but don't know how to implement it correctly.
My Controller function:
public function verify(AusleihRequest $request){
$this->middleware('guest');
$validator = Ausleih::make($request->all(), [
'seriennummer' => 'required'
]);
return redirect()->route('ausleihe.yourdevices')
->with('success','Gerät erfolgreich verifiziert');
}
EDIT:
And the user shouldn't have to log in again after verifying.
Use the exists rule:
The first param after the : specifies the name of your table, the second (after the ,) the name of the field, the number is stored.
$validator = Ausleih::make($request->all(), [
'seriennummer' => 'required|exists:serialnumbers,number' // or however your field is named
]);
https://laravel.com/docs/master/validation#rule-exists

Laravel how to validate data in one row, not checking in whole table

I'm not sure if I explained briefly what's the problem is about.
I have a user voting form in which user passes his first name,surname,mothers' surname, and ID.
I have also a table users which stores all this data. Yesterday I found a bug or I misunderstood how laravel validation works because it passes submit every time when it find all the data existing in table.
This is a table with two records.
EXAMPLE
What i expected from validation was to check if the ID=98111091239 name=Andrzej surname=Pianowski and mother surname =Mila and only if everything is correct and exists in one row then the vote can be made.
Instead i can pass ID from first row, other things from second and it also will allow user to vote.
Is that a bug, laravel works that way or what?
I'm really looking forward for any tip,help,sugestions.
And here's validation rule i'm using
/*This validates whether all data is correct */
$validator = Validator::make($request->all(),[
//check whether such pesel exists in votes and in voters
'pesel' =>'required|exists:wyborca|max:11|min:11',
'imie' =>'required|exists:wyborca|max:64|min:2',
'nazwisko' => 'required|exists:wyborca|max:128|min:2',
'nazwisko_matki' => 'required|exists:wyborca|max:128|min:2'
]);
if($validator->fails())
{
return back()
->with('errors','Wprowadzono nieprawidłowe dane')
->withInput();
}
The validator seems to be passing since those values probably exist in multiple records and not just a single one.
One solution would be to validate to ensure that all the fields are present in the request and then do a simple Eloquent query to check if the record exists:
$user = App\User::where('id', $request->id)
->where('name', $request->name)
->where('surname', $request->surname)
->where('mother', $request->mother)
->exists(); //true or false
if($user){
//vote
}
return response()->json(['error' => 'user not found'], 404);
If it does exist, cast the vote else return an error.

PHP Laravel 5 Making Validator Rule to check if account with specific type exists

I'm struggling with making this validation rule. In my 's_accounts' table I have two rows: acc_name (stores the name of the account) and acc_type (stores the type of account). Before when I was working with only one account type I had created the following validator rule which made sure that the acc_name was unique:
$rules = array('acc_name' => 'unique:s_accounts,acc_name');
$input['acc_name'] = $username;
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
// account already exists
}
else {
// proceed
}
Now that my application can make two types of accounts, i want it to be able to have two accounts with the same acc_name as long as the acc_type is different. In order to do this, i need to change this validation rule to include $input['acc_type'] = "X";
What i need help with is changing the rule array so validation fails if an account with the same acc_name and acc_type exists but doesn't fail if the acc_name with a different acc_type exists?
You can add it as additional parameters to the unique rule:
$rules = ['acc_name' => 'unique:s_accounts,acc_name,NULL,id,acc_type,x'];

How do I make a form field not neccessray for validation in Symfony?

I have 2 forms: $patientForm and $investigationForm.
They are both combined into one view, so the user fills in the fields and 2 records are created in Patient table and Investigation table. Investigation table has a foreign key - to the patient name. So one patient can have many investigations.
So I obviously need the patient id to add it to an investigation record as a foreign key. However, the patient id isn't created until the patient form is saved.
So I have devised the following function:
protected function processPatientInvestigation(sfWebRequest $request, sfForm $investigationForm, sfForm $patientForm)
{
$patientForm->bind($request->getParameter($patientForm->getName()), $request->getFiles($patientForm->getName()));
if ($patientForm->isValid() && $investigationForm->isValid() ) {
$patientForm->save();
$values = $request->getParameter($investigationForm->getName());
$values['patient_id'] = $patientForm->getObject()->getId();
$investigationForm->bind($values, $request->getFiles($investigationForm->getName()));
$investigationForm->save();
}
The if statement always fails because $investigationForm isn't valid until I give its form field a patient_id value. So this value is empty at this point. However, if I just took the isValid() check out for $investigation form and put it down later on after the $patientForm is saved. This means that if it failed validation and the user had missed a field, when they don't click submit again, the whole function would run again meaning we'd have duplicate patient records.
So what I think the answer is, is making the patient_id field not be validated, so it can be empty and still pass the isValid() function.
Please let me know if this isn't clear. Hope you can advise!
Try the following though this should really be done in the forms configure method.
$patientForm->getValidator('patient_id')->addOption('required', false);
The cleaner solution would be to set all your validation rules in the /lib/form/*Form.class.php file itself (rather than manipulating it in your action).
$this->validatorSchema['patient_id'] = new sf*Validator(array(
'required' => false
), array());
If you just want to let a form field completely unvalidated, use
$this->validatorSchema['patient_id'] = sfValidatorPass()
I'd go with embedded forms and let symfony handle the saving correctly.

Categories