lumen validation: rule for value not exists in database - php

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

Related

Validation in Laravel on relationship

In Laravel, I have a persons model that has a many-to-many relationship with its group. The person's name needs to be unique in its group but not on the persons table. How would ensure that?
My validation is done in the controller store method using $request->validate(['name => ...
I currently save the new person in a controller using simply - Person::create([...
My simple approach is using a composite primary keys on pivot table and use basic exception handling like try catch stuff whenever inserting data is fail due to migration
$table->foreignId('group_id') // Add any modifier to this column
$table->foreignId('person_id') // Add any modifier to this column
$table->primary(['group_id', 'person_id']);
If you want to do it on controller, make sure to setup relationship. Then just use Rule::notIn() Validation
'name' => [
'required',
Rule::notIn(/* put your logic here */),
],
You can use 'exist' rule in Laravel Validation like that:
'name' => 'exists:group,name,person_id,'.$id
For more info you can check here:
https://laravel.com/docs/9.x/validation#rule-unique

Codeigniter 4 is_unique rule validation throws not unique error when I update record

I have a simple form that stores some data in the database and for the Title field I have an is_unique validation rule along with others. Following are my validation rules from the TaskModel:
protected $validationRules = [
'Title' => 'required|min_length[5]|max_length[15]|is_unique[tasks.Title]',
'Description' => 'required|max_length[300]',
'CreatedAt' => 'required',
'UpdatedAt' => 'required',
'DueDate' => 'required|ValidateDueDate[DueDate]',
'AssignedTo' => 'required',
'Author' => 'required'
];
Now everything is working as intended when adding data to the Database. The Problem is when I try to update a record let's say I change the author name and when I submit the form it says the title should be unique. I want it to ignore the record row from the database I am editing and check input's uniqueness with others. Can you help me achieve this? I am thinking of passing the record id with the form and ignoring it when checking uniqueness but I don't know how to pass the Id to the validation rule.
You can pass the Id of row as parameter in the is_unique rule. Like
is_unique[tasks.Title,Id,{Id}]
Hope this helps :)
UPDATE: More Detailed Explanation
Second parameter Id is database field name. Third one is the Id that is passed from the form. For this purpose add a hidden field in the edit form then set its name = Id and its value=$data['Id']. Where $data['Id'] is the Id of the row fetched from the Database and passed to the view. So when the form will be submitted and Id will be submitted in $_POST. Which is then passed to rule parameter as:
{Id}
HOPE THIS HELPS :(

How to make conditions on laravel form request

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');

Use Laravel validations when html input names vary from column name

I cannot get passed required validation in my Laravel app.
This is the validation rule I have...
$rules = [
'email' => 'required|unique:members|max:100',
];
The specific column name is email. The HTML page input field name is emailAddress
What to do in these situations ? How to tell this validation which request field to check ?
Thanks!
Found the problem...
It's the input field names that validation checks. Not column names.
The problem here is the unique validation rule of the email field. I had to speficify which column to check for already stored emails.
Like this
unique:members,email
I had to use the column name after the table name separated by a , (comma).
So, the rule will be like
$rules = [
'emailAddress' => 'required|unique:members,email|max:100',
];
That's it!
You don't check against column names in validation, just use the input name.
$rules = [
'emailAddress' => 'required|unique:members|max:100',
];
I guess to be more clear: the Request instance is what is checked. Validation doesn't interact with the database, it interacts with the Request
You can change the name attribute to email.
Or you can use validation rules like this:
'emailAddress' => 'required|unique:members|max:100',
And then in controller method do this:
Model::create([
'email' => $request->emailAddress,
]);

laravel how to specifiy the input columns

I have a form in html that has an input with name restaurantName, but my column in the database is name. I am not able to use this in the controller
Restaurant::create(Input::only('restaurantName'));
Because there is no column with restaurantName so my question is how to tell laravel that restaurantName is maped to name ?
many thanks
Edit
the html form has these fields:
restaurantName
website
username
password
mobileNumber
firstName
lastName
The database has two tables which are Admin and Restaurant, each restaurant has one admin and the admin is one for each restaurant, so it is one to one relationship
when I submit the form I do the following:
$input = Input::all();
$admin = Admin::create(Input::only('username', 'password', 'mobileNumber', 'firstName', 'lastName'));
$data = ['name' , Input::get('restaurantName'), 'website' => Input::get('website')];
$restaurant = new Restaurant($data);
$admin->restaurant()->save($restaurant);
the admin row is inserted to the database so the problem starts with the $data line code.
the exception is:
BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::save()
Firstly, you should never just blindly pass user input to models, and secondly, this particular problem has absolutely nothing to do with laravel.
Your problem can be solved with basic PHP. Simply, create your own array of input.
$data = [
'field' => Input::get('field'),
'name' => Input::get('restaurantName')
];
There seems to be a grave misconception that Laravel is its own independant system, it is not. It is literally a collection of PHP code, it doesn't do anything that can't be done with PHP and it doesn't prevent you from doing anything you can normally do with PHP.

Categories