felixkiss / uniquewith-validator Goto Github PK
View Code? Open in Web Editor NEWCustom Laravel Validator for combined unique indexes
License: MIT License
Custom Laravel Validator for combined unique indexes
License: MIT License
I am using Laravel 5.3
and the following code doesn't work
$validator = Validator::make($request->all(), [
'person.*.email' => 'email|unique_with:users,person.*.email=email',
'person.*.first_name' => 'required_with:person.*.last_name',
]);
It keeps showing and error message saying:
Unknown column 'person.0.email' in 'where clause'
Hello,
I have custom validators set on my project. When required your package, this custom validator overwrites all mine.
Any idea why this is the case ?
Thanks
Since the update to version 1.1.2, I'm always getting the following failing validation when trying to save a model with a custom validator:
unique_with: [This combination of :fields already exists., This combination of :fields already exists.,โฆ]
0: "This combination of :fields already exists."
1: "This combination of :fields already exists."
2: "This combination of :fields already exists."
The model giving this error does not even have a unique_with
validator. Going back to version 1.1.1, this error is not present (with exactly the same code).
I have a table like this
Schema::create('courseschedueles', function (Blueprint $table) {
$table->date('date');
$table->time('starttime');
$table->time('endtime');
$table->integer('subject_id')->unsigned()->index();
$table->foreign('subject_id')->references('id')->on('subjects')->onDelete('cascade');
$table->integer('hall_id')->unsigned()->index();
$table->foreign('hall_id')->references('id')->on('halls')->onDelete('cascade');
$table->timestamps();
$table->primary(['date', 'starttime', 'endtime', 'hall_id']);
});
I would like to include 'date', 'starttime', 'endtime', 'hall_id' in my composite key and validate it. A help please
For whatever reason i cant for the life of me make my codeception tests respect the unique_with rules. if i post the same data using an http client, i get the expected validation errors, but using codeception it seems to bypass it entirely and just return a database constraint error.
Any suggestions?
UPDATE: it seems this issue is because I'm not including one of the unique values in the POST input, its actually a get variable found in the url.
IE: i'm updating /member/1/hobbies
And want to check that the provided data does not create a duplicate of member 1 and a given hobby.
Is this the intended result?
Still dont get why it works with an http client, and not trough codeception though.
.
the validation is working fine but I get validation error as
" uniquewith-validator::validation.unique_with"
I set
"unique_with" => 'This combination of :fields already exists.',in validation file
but doesn't appear at all
Hello,
I am using unique_with validator and a custom validator in two different controller. The Validator::resolver is creating a problem. If i remove this resolver for my Custom Validator then unique_with is working & if i put it in global.php then unique_with is not working. Please help..
I want to validate multiple fields, i can do this with this:
$rules['en.title'] = 'required|between:4,65|unique_with:product_translation, en.title = title, '.$id.' = product_id';
But i want to set combination field and the custom name, how does this work? I have the field "locale" thats the combination field and i have als title in place of en.title.
I am not able to make unique_with work for UPDATE request, where I need to ignore the current existing foreign keys for the rows, how can I do that?
Hi,
did anything how described (using laravel 4), but it yields
Class 'Felixkiss\UniqueWithValidator\UniqueWithValidatorServiceProvider' not found
Any idea?
Thanks and greets
SQL fail using 'channel.name' as column. 'channel.name' is a HTML form with format channel[name]
:
return [
'channel.name' => [
'required',
'min:3',
'max:255',
'unique_with:channels,name,product_id,'.$this->route('channel')
],
'channel.product_id' => 'required',
];
Hi @felixkiss
Is it possible for three columns unique check? Coz I need that feature for the my current project.
Thanks
Hello, in case of using with models that have a non-standard id
primary key column name this validator will fail, in $verifier->getCount() its possible to pass this alternative column name ( at the moment you sending null parameter on this place ). It could be more correct to check if model have a $primaryKey set up, and use it value in this case, or at least get it as last value in validator parameters... For example:
$ignore_id = null;
$ignore_id_column_name = null;
if ($parameters_length > 1)
{
$pre_last_param = $parameters[$parameters_length-2];
$pre_last_param_value = str_replace(" ", "", $parameters[$parameters_length-2]);
$last_param = $parameters[$parameters_length-1];
$last_param_value = str_replace(" ", "", $parameters[$parameters_length-1]);
if (preg_match('/^[1-9][0-9]*$/', $last_param_value))
{
$last_param_value = intval($last_param_value);
if ($last_param_value > 0)
{
$ignore_id = $last_param_value;
$parameters_length--;
}
} elseif (preg_match('/^[1-9][0-9]*$/', $pre_last_param_value)) {
$pre_last_param_value = intval($pre_last_param_value);
if ($pre_last_param_value > 0)
{
$ignore_id = $pre_last_param_value;
$ignore_id_column_name = strval($last_param_value);
$parameters_length=-2;
}
}
}
Im a newbie, the code is very fast and ugly example, sorry.
Is it a new Error?
Great bundle, but how i gonna make the 2 variable from updates value:
'first_name' => 'required|unique_with:users,last_name,2',
It depend on the id in the url.
I do have multiple database connections since I am in a multi tenant environment. Therefore I do have to specify the connection name for the validation rule:
'job_nr' => 'required|max:255|unique_with:tenant_connection.jobs,name'
But I always get a SQLSTATE[42S02]: Base table or view not found
- error.
It is possible to specify the connection name somehow?
I've added a rule:
'name' => 'required|unique_with:templates,organisation_id|min:2'
And I have data:
name='test', organisation_id=2
And when I try to add name='test' with organisation_id 1, it fails.
The validator is firing for me with any update because I have Model level validation. Could you add something to detect that the validation should not run if the id of the model is the duplicate it is detecting.
when include this service in composer I got this message. Seems related to Laravel 4.1
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Conclusion: remove laravel/framework v4.1.11
- Conclusion: don't install laravel/framework v4.1.11
- Conclusion: don't install laravel/framework v4.1.10
- Conclusion: don't install laravel/framework v4.1.9
- Conclusion: don't install laravel/framework v4.1.8
- Conclusion: don't install laravel/framework v4.1.7
- Conclusion: don't install laravel/framework v4.1.6
- Conclusion: don't install laravel/framework v4.1.5
- Conclusion: don't install laravel/framework v4.1.4
- Conclusion: don't install laravel/framework v4.1.3
- Installation request for felixkiss/uniquewith-validator dev-master -> sati
sfiable by felixkiss/uniquewith-validator[dev-master].
- Conclusion: don't install laravel/framework v4.1.2
- Conclusion: don't install laravel/framework v4.1.1
- felixkiss/uniquewith-validator dev-master requires illuminate/support 4.0.
x -> satisfiable by laravel/framework[v4.0.0, v4.0.1, v4.0.10, v4.0.2, v4.0.3, v
4.0.4, v4.0.5, v4.0.6, v4.0.7, v4.0.8, v4.0.9], illuminate/support[v4.0.0, v4.0.
1, v4.0.10, v4.0.2, v4.0.3, v4.0.4, v4.0.5, v4.0.6, v4.0.7, v4.0.8, v4.0.9].
- don't install illuminate/support v4.0.0|don't install laravel/framework v4
.1.0
- don't install illuminate/support v4.0.1|don't install laravel/framework v4
.1.0
- don't install illuminate/support v4.0.10|don't install laravel/framework v
4.1.0
- don't install illuminate/support v4.0.2|don't install laravel/framework v4
.1.0
- don't install illuminate/support v4.0.3|don't install laravel/framework v4
.1.0
- don't install illuminate/support v4.0.4|don't install laravel/framework v4
.1.0
- don't install illuminate/support v4.0.5|don't install laravel/framework v4
.1.0
- don't install illuminate/support v4.0.6|don't install laravel/framework v4
.1.0
- don't install illuminate/support v4.0.7|don't install laravel/framework v4
.1.0
- don't install illuminate/support v4.0.8|don't install laravel/framework v4
.1.0
- don't install illuminate/support v4.0.9|don't install laravel/framework v4
.1.0
- Can only install one of: laravel/framework[v4.1.0, v4.0.0].
- Can only install one of: laravel/framework[v4.1.0, v4.0.1].
- Can only install one of: laravel/framework[v4.1.0, v4.0.10].
- Can only install one of: laravel/framework[v4.1.0, v4.0.2].
- Can only install one of: laravel/framework[v4.1.0, v4.0.3].
- Can only install one of: laravel/framework[v4.1.0, v4.0.4].
- Can only install one of: laravel/framework[v4.1.0, v4.0.5].
- Can only install one of: laravel/framework[v4.1.0, v4.0.6].
- Can only install one of: laravel/framework[v4.1.0, v4.0.7].
- Can only install one of: laravel/framework[v4.1.0, v4.0.8].
- Can only install one of: laravel/framework[v4.1.0, v4.0.9].
- Installation request for laravel/framework 4.1.* -> satisfiable by laravel
/framework[v4.1.0, v4.1.1, v4.1.10, v4.1.11, v4.1.2, v4.1.3, v4.1.4, v4.1.5, v4.
1.6, v4.1.7, v4.1.8, v4.1.9].
The Validator assumes that id's can only be integers but what if I use UUID
as id's in the database
After merging #15, I noticed there are no tests for ValidatorExtension#replaceUniqueWith
๐
Need to implement them.
Not sure, about why I had cache problems with the package. I'm using Laravel 5.3. I was having problems using the package. It doesn't find it when I was using it. A message "Method not found" reported the system. Adding manually to bootstrap/cache/config.php the next line
29 => 'Felixkiss\UniqueWithValidator\UniqueWithValidatorServiceProvider',
resolved the problem. Maybe somethe bad config in the app?? Thank for the package, very useful
Hi,
I am trying to validate multiple records before inserting it all.
// Currently using the facade validator
use Illuminate\Support\Facades\Validator;
$data = [
'items' => [
['bID' => 1, 'slot' => 2],
['bID' => 2, 'slot' => 2]
]
];
// bID and slot are unique.
$v = Validator::make($data, [
'items.*.bID' => 'required|unique_with:samples, slot'
]);
if ($v->fails()) {
return response()->json([$v->errors()]);
}
return response()->json(['success']);
The unique_with
doesn't seem to work for me.
When I run it, I get an error:
Am I using the wrong validator?
I tried to override the error message following this guide : http://laravel.com/docs/validation#custom-error-messages but it didn't work.
Any ideas ?
I keep getting the following error message:
ReflectionException in Container.php line 736:
Class validator does not exist
The Service Provider should probably look something like this (https://laravel.com/docs/5.2/validation#custom-validation-rules):
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Validation\Factory;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot(Factory $factory)
{
$this->loadTranslationsFrom(
__DIR__ . '/../../lang',
'uniquewith-validator'
);
$factory->extend('unique_with', 'ClassName@validate');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
}
With a softDelete-enabled model uniquewith will fail validation if a uniqueness exists even if the entry is in a deleted state (a filled 'deleted_at' field).
In my ProductRequest.php I have set this:
public function rules()
{
return [
'name' => 'required|min:3|unique_with:products,category_id',
'price' =>'required'
];
}
And in my ProductsController.php I have this:
public function update(Product $product, ProductRequest $request)
{
$product->update($request->all());
return redirect('products');
}
But when I try to Update a field, like product's price, it gives me the message:
This combination of name, category id already exists.
Could someone help me?
I'm using the latest laravel with the CVE patch, will report back what triggers this issue.
EDIT 2: I've tried version *.21, *.18, *.0 and they render the same error.
<h1>Whoops, looks like something went wrong.</h1>\n
<h2 class="block_exception clear_fix">\n
<span class="exception_counter">1/1</span>\n
<span class="exception_title"><abbr title="BadMethodCallException">BadMethodCallException</abbr> in <a title="/project/test/vendor/laravel/framework/src/Illuminate/Validation/Validator.php line 1096">Validator.php line 1096</a>:</span>\n
<span class="exception_message">Method [trans] does not exist.</span>\n
</h2>\n
<div class="block">\n
<ol class="traces list_exception">\n
<li> in <a title="/project/test/vendor/laravel/framework/src/Illumina
As Laravel supports registering only one validator service provider, it would be nice if this plugin uses extend method to register validator:
Validator::extend('unique_with', '\Felixkiss\UniqueWithValidator\ValidatorExtension@validateUniqueWith');
Now it obviously won't work.
At the moment if we use this validator, we cannot register any validator service provider and if someone else used this method using service provider it will be impossible to use those 2 validators
I define all of my standard validation error messages in /app/lang/{language}/validation.php
but if I add unique_with
it still shows your error message. Is it possible to override your message globally? Don't want to do it manually on every validation.
Would be nice to have this on the laravel standard.
Would you be so kind to consider making this a deferred service, because not every request needs a validator.
The Validator
itself is also deferred.
hi,
thank you for your amazing validator since laravel still lack of it. but when I try to use it on my project (laravel 4) and follow all the instruction, I got this error:
"Maximum function nesting level of '100' reached, aborting"
It seem the problem is on the register function (Felixkiss\UniqueWithValidator\UniqueWithValidatorServiceProvider).
I have tried again on a clean laravel 4 project, the same problem.
Pls notice that even though I don't use the 'uniqueWith' rule for validation, the error still occurs.
Maybe you can take a look ?
The title may be misleading, and I will try to explain this with an example.
This discussions started in pull #73 (see last comments). I have added @felixkiss's suggestion, but it didn't work.
Assume you have:
$data = [ "user_id": [ 1, 3 ], "post_id": 1 ];
$rules= [ 'user_id.*' => 'unique_with:post_user, user_id.* = user_id, post_id' ];
$validator = Validator::make($data, $rules);
The error that I get is:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id.0' in 'where clause' (SQL: select count(*) as aggregate from
post_user
whereuser_id
.0
= 1 andpost_id
= 1)"
So, it seems to me that the wildcard in user_id.* = user_id
is not being processed when the array is non associative.
Please let me know if this is simply me doing something wrong, or is indeed an issue.
Thank you
Seems like UniqueWithValidatorServiceProvider validator resolver is not doing it's thing.
I'm trying to achieve the following validation:
'data.attributes.mail-address' => [
'email',
'max:255',
sprintf(
'unique_with:employees,data.attributes.mail-address = mail_address,%s = customer_id',
$user->getAttribute('customer_id')
),
],
A mail address should be unique to the customer the employee is assigned to. Is this somehow possible to achieve?
It should call the rule for unique_with, whether or not the other unique_with fields were updated.
Last dependency preventing upgrade. Any chance of making compatible with 4.1?
I have a custom validator registered in global.php
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new CustomValidator($translator, $data, $rules, $messages);
});
CustomValidator.php
class CustomValidator extends Illuminate\Validation\Validator {
Which is causing the following: "Method [validateUniqueWith] does not exist."
Removing my custom validator and your package works fine.
How can I use both without conflict?
Hi,
I have 3 field must be unique with each other. First one is string (varchar) another two fields are encrypted numbers. Is there any possible way to write decrypted value in to validation ? I will give you my request example code below thanks.
public function rules()
{
if ($this->get('unit') != null) {
$unit_id = Crypt::decrypt($this->get('unit'));
$level_id = Crypt::decrypt($this->get('level'));
}
switch ($this->method()) {
case 'POST':
$rules['printable_name'] = 'required|unique_with:printables,printable_name=name,level_id,unit_id';
$rules['slug_name'] = 'required|unique:printables,slug';
$rules['parent_note'] = 'required';
$rules['teacher_note'] = 'required';
$rules['printable_file'] = 'required';
$rules['parent_note'] = 'required';
$rules['level'] = 'required';
$rules['unit'] = 'required';
return $rules;
break;
case 'PUT':
$id = Crypt::decrypt($this->get('id'));
$rules['printable_name'] = 'required|unique_with:printables,printable_name=name,level_id,unit_id' . $id;
$rules['slug_name'] = 'required|unique:printables,slug,' . $id;
$rules['parent_note'] = 'required';
$rules['teacher_note'] = 'required';
$rules['parent_note'] = 'required';
$rules['level'] = 'required';
$rules['unit'] = 'required';
$this->get('printable_file_hidden') == 1 ? $rules['printable_file'] = 'required' : $rules['printable_file_hidden'] = 'required';
return $rules;
break;
}
}
I want to une unit_id and level_id in my unique_with validation , I don't want to remove crypt because security is my first priority.Thanks
I'm currently developing an API and the keys, of the incoming JSON data that have to be validated, do not match the actual database column names.
Incoming JSON for a POST request may look like this:
{
"data": {
"attributes": {
"date": "2017-08-25"
},
"relationships": {
"employee": {
"set": "202"
}
}
}
}
As the documentation describes I would check if the column date
is unique with the column employee_id
but I actually would need to check if data.attributes.date
is unique with employee_id
.
So ...
'<field1>' => 'unique_with:<table>,<field2>[,<field3>,...,<ignore_rowid>]',
... would become ...
'data.attributes.date' => 'unique_with:<table>,employee_id',
Is there any chance that the unique_with
validator could look like this: (?)
'<custom_field_name>' => 'unique_with:<table>,<field1>,<field2>[,<field3>,...,<ignore_rowid>]',
Stacktrace:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'data.attributes.date' in 'where clause' (SQL: select count(*) as aggregate from `employees` where `data`.`attributes`.`date` = 2017-08-25)
$this->validate($request, [
'url' => 'required|unique_with:table_xxx,project_id',
]);
QueryException:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'http://example.com' for key 'composite_constraint' (SQL: insert into table_xxx
(url
,project_id
) values (http://example.com,1))
I am using the uniquewith validation without a problem in my application. I am trying to write some tests now. However, when I try to run a test in PHPUnit it gives me the following error:
BadMethodCallException: Method [validateUniqueWith] does not exist
What do I need to do in order for this to work in my unit tests?
Thanks
If value of the column in unique_with is 0, it always returns unique even if that combination already exists.
Illuminate\Foundation\ComposerScripts::postInstall
> php artisan optimize
[Symfony\Component\Debug\Exception\FatalThrowableError]
Class 'Felixkiss\UniqueWithValidator\UniqueWithValidatorServiceProvider' no
t found
Script php artisan optimize handling the post-install-cmd event returned with error code 1
I recently upgraded the package from version 2.* to 3 and faced this issue. I have already changed the name of the service provider on the config/app.php file. Very curious as to why it's happening. I am on laravel 5.4 btw, also funny thing is I managed to install it on my local homestead without any issues.
Hello, I already used the validator in Laravel 4.2, I'm starting to upgrade to L5.2, did the installation as the documentation ran the 'update composer', and checked that the folder was created on vendors, but when adding the service provider 'Felixkiss \ UniqueWithValidator \ UniqueWithValidatorServiceProvider 'and run composer update again, the following error occurs:
[ReflectionException]
Class validator does not exist
Script php artisan clear-compiled handling the pre-update-cmd event returned with an error
I also tried adding the service provider as follows:
Felixkiss\UniqueWithValidator\UniqueWithValidatorServiceProvider::class
But the error remains.
Thanks a lot for the help
I am trying something like this:
'moviePeople.*.person' => 'required|exists:people,id|unique_with:movie_people,moviePeople.*.person = person_id,role',
That gives me following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'moviePeople.0.person' in 'where clause' (SQL: select count(*) as aggregate from `movie_people` where `moviePeople`.`0`.`person` = 1 and `person_id` is null and `role` is null)
It's awesome that somebody started building one of these; I was really bummed that Laravel 4 didn't have this built-in.
However, unlike all the Laravel built-in functions, you don't seem to give a way to specify that the the field being validated has a different name in the database. Could this possibly be added? I mean, it is possible to just adapt the data being validated so that it matches the database-names, but it really is a hack-around.
I was using your functionality and it worked perfectly but after a recent update I noticed that the unique_with validation is always returning me "true". I'm sorry I cannot be more specific on my code, but I can assure you I was using it correctly as your guide says.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.