Larave validate column to be always unique whatever value is - php

So i have table with columns: id, user_id, value value is not always something fixed. if it is for example: EUR. all records for user_id must be EUR. how to validate this maybe in migration?

Use Custom Validation Rules https://laravel.com/docs/9.x/validation#using-rule-objects
$request->validate([
'currency' => ['required', 'string', new CurrencyRule],
]);

Related

Laravel 8 unique validation rule doesn't work with user_id

I'm using Laravel 8 and the unique validation rule to ensure that a record remains unique, I'm now trying to extend this so that it's unique per user as well, but when expanding the functionality and using the rule in array form it doesn't seem to validate the user ID and instead gives me a integrity constraint violation.
So I have a table called brands, and this table contains two columns in question: brand and user_id, I need to ensure that when storing a record that the brand is unique against the brand column and that the logged in in user's ID the one making the request, e.g:
Two users can have the same brand, but a single user can't have multiples of the same brand.
$validator = Validator::make($request->all(), [
'brand' => [
'required',
'string',
Rule::unique('brands')->where(function ($query) {
return $query->where('user_id', Auth::id());
})
],
'url' => 'required|string',
'telephone' => 'required|string|min:11|max:11'
]);
I've also tried:
'brand' => 'required|string|unique:brands,brand,user_id,' . Auth::id()
What am I missing?
According to the documentation you have to use the ignore() function:
Rule::unique('users')->ignore($user->id),
on your case:
Rule::unique('brands')->ignore($user->id, 'user_id'),

How to make Laravel unique validation work on an input array?

UpdateEntityRequest.php:
'phones' => 'sometimes|nullable|array',
'phones.*.id' => 'sometimes|required|integer|distinct|exists:entity_phones,id,entity_id,'.$this->id,
'phones.*.number' => 'required|alpha_num|max:255|distinct|unique:entity_phones,number,'.$this->id.',entity_id',
entity_phones table:
id, number, entity_id.
unique constraint: (number, entity_id)
EntityRepository.php:
foreach ($attributes['phones'] as $phone) {
if (isset($phone['id'])) {
$entity->phones()->updateOrCreate([
'id' => $phone['id'],
'entity_id' => $entity->id
], $phone);
} else {
$entity->phones()->create($phone);
}
}
My entity can have more than phone associated, but not a repeated number. My intention is to check the unique (entity_id, number) in the UpdateEntityRequest.php so:
If the phone object comes without an id, it should check that the combination of number, entity_id doesn't exists. But the number can exist with other entity_id.
If the request comes with an id, it should check that the combination of number, entity_id doesn't exists only in other ids, but ignore the given id.
I'm having trouble witht the Laravel Unique rule validating only when i want it to make the validation. Any ideas how could I make this solution would be appreciated.
If you need to ignore a given ID during the unique check try using the Rule class to fluently define the rule.
use Illuminate\Validation\Rule;
Validator::make($request_data, [
'number' => [
'required',
'alpha_num', (...all your other rules)
Rule::unique('entity_phones')->ignore($entity_id),
],
]);
You can read more in laravel docs about unique rule in paragraph: Forcing A Unique Rule To Ignore A Given ID.
I ended up doing this:
$phoneIds = $this->input('phones.*.id');
'phones.*.number' =>
[
'required_with:phones',
'alpha_num',
'max:255',
'distinct',
Rule::unique('entity_phones', 'number')
->where('entity_id', $this->id)
->where(function ($query) use ($phoneIds) {
return $query->where('id', '!=', array_shift($phoneIds));
})
],

Laravel different validation doesn't work with strings containing numbers

I want to validate a value that I got from a certain form. The value type is text. I want it to match a specific username from the database from the users table, but also to not match the current user's username.
To achieve that, I used the following validation rules:
'username' => [
'required',
'string',
'exists:App\User,username',
'different:' . auth()->user()->username
]
What I've discovered is that whenever the auth()->user()->username value includes a digit, it passes the validation even if request()->username = auth()->user()->username. Is there anything I can do to prevent this from happening?
Thanks in advance.
Use unique like -
Considering id is your user's id.
'username' => 'required|string|unique:username,id,'.auth()->user()->username,
This will check if username is unique or not except this userId.
The answer to this issue was creating own Rule::exists validation, which is shown below:
'username' => [
'required',
'string',
Rule::exists('users')->where(function ($query) {
$query->where('username', '<>', auth()->user()->username);
})
],
I solved a similar problem as follows.
$request->validate([
'email' => ['required', 'email','unique:users,email,'.Auth::id()],
'phone' => ['required', 'unique:users,phone,'.Auth::id()],
]);

Laravel Unique keyword for particular Column

I'm using "unique" keyword for validating unique users for employee_id in controllers, in my database there is column called company_id , while adding new user they will be set us some company_id ,when i add new user for my company employee id will be unique for my company itself , if employee_id is 4 for another company and i'm adding 4 for my company it must accept , it will check only for that particular company only.
$this->validate($request,
[
'name' => 'required',
'emp_id' => 'required|unique:users', (Here how can i check for particular company)
'email' => 'required|unique:users',
'role' => 'required',
]);
can anyone please help me ???
You should use the array syntax here and use a "custom" unique rule:
'emp_id' => [ "required", Rule::unique('users')->where(function ($query) use ($request) {
$query->where('emp_id', $request->emp_id)->where("company_id",$request->company_id);
}) ]
Something like this anyway
If emp_id and company_id is in request
'emp_id' => 'required|unique:users,emp_id|unique:users,company_id',
Check in docs : https://laravel.com/docs/master/validation#rule-unique
I assume emp_id and company_id are present in users table and you are sending in request

Laravel 5 Unique form validation ignore id / slug

These are my rules in my class:
class AppointmentsController extends Controller
{
protected $rules = [
'appointment' => ['required', 'min:5'],
'slug' => ['required', 'unique:appointments'],
'description' => ['required'],
'date' => ['required', 'date_format:"Y-m-d H:i"'],
];
This is in the laravel official docs:
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:
'email' => 'unique:users,email_address,'.$user->id.',user_id'
I tried using this in my rules:
'slug' => ['required', 'unique:appointments,id,:id'],
This indeed ignores the current row BUT it ignores it completely. What I want to accomplish is, I want it to ignore the current row only if the slug is unchanged. When it is changed to something that is already unique in another row, I want it to throw an error.
The Unique validator works like that
unique:table,column,except,idColumn
So in your case, you can do it like that:
Get the id you want to validate against, you can get it from the route or with any other way that works for you; something like that
$id = $this->route('id');
'slug' => ['required','unique:appointments,slug,'.$id],
For example we need to update contact info into Users table.
In my model User I created this static method:
static function getContactDataValidationRules( $idUserToExcept ) {
return [
'email' => 'required|email|max:255|unique:users,email,' . $idUserToExcept,
'pec' => 'required|email|max:255',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:8|max:20',
'mobile' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:8|max:20',
'phone2' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:8|max:20',
'recovery_email' => 'required|email|max:255',
];
}
and in my UsersController, into the method that update User I've:
$id = $request->input('id');
$request->validate(User::getContactDataValidationRules( $id ));
:-)

Categories