Custom Laravel Validator for combined unique indexes

Overview

unique_with Validator Rule For Laravel

Build Status

This package contains a variant of the validateUnique rule for Laravel, that allows for validation of multi-column UNIQUE indexes.

Documentation for older versions

Installation

Install the package through Composer. On the command line:

composer require felixkiss/uniquewith-validator

Configuration

Add the following to your providers array in config/app.php:

'providers' => [
    // ...

    Felixkiss\UniqueWithValidator\ServiceProvider::class,
],

Usage

Use it like any Validator rule:

$rules = [
    '<field1>' => 'unique_with:<table>,<field2>[,<field3>,...,<ignore_rowid>]',
];

See the Validation documentation of Laravel.

Specify different column names in the database

If your input field names are different from the corresponding database columns, you can specify the column names explicitly.

e.g. your input contains a field 'last_name', but the column in your database is called 'sur_name':

$rules = [
    'first_name' => 'unique_with:users, middle_name, last_name = sur_name',
];

Ignore existing row (useful when updating)

You can also specify a row id to ignore (useful to solve unique constraint when updating)

This will ignore row with id 2

$rules = [
    'first_name' => 'required|unique_with:users,last_name,2',
    'last_name' => 'required',
];

To specify a custom column name for the id, pass it like

$rules = [
    'first_name' => 'required|unique_with:users,last_name,2 = custom_id_column',
    'last_name' => 'required',
];

If your id is not numeric, you can tell the validator

$rules = [
    'first_name' => 'required|unique_with:users,last_name,ignore:abc123',
    'last_name' => 'required',
];

Add additional clauses (e.g. when using soft deletes)

You can also set additional clauses. For example, if your model uses soft deleting then you can use the following code to select all existing rows but marked as deleted

$rules = [
    'first_name' => 'required|unique_with:users,last_name,deleted_at,2 = custom_id_column',
    'last_name' => 'required',
];

Soft delete caveat:

In Laravel 5 (tested on 5.5), if the validation is performed in form request class, field deleted_at is skipped, because it's not send in request. To solve this problem, add 'deleted_at' => null to Your validation parameters in request class., e.g.:

protected function validationData()
{
    return array_merge($this->request->all(), [
        'deleted_at' => null
    ]);
}

Specify specific database connection to use

If we have a connection named some-database, we can enforce this connection (rather than the default) like this:

$rules = [
    'first_name' => 'unique_with:some-database.users, middle_name, last_name',
];

Example

Pretend you have a users table in your database plus User model like this:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateUsersTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function(Blueprint $table) {
            $table->increments('id');

            $table->timestamps();

            $table->string('first_name');
            $table->string('last_name');

            $table->unique(['first_name', 'last_name']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }

}
<?php

class User extends Eloquent { }

Now you can validate a given first_name, last_name combination with something like this:

Route::post('test', function() {
    $rules = [
        'first_name' => 'required|unique_with:users,last_name',
        'last_name' => 'required',
    ];

    $validator = Validator::make(Input::all(), $rules);

    if($validator->fails()) {
        return Redirect::back()->withErrors($validator);
    }

    $user = new User;
    $user->first_name = Input::get('first_name');
    $user->last_name = Input::get('last_name');
    $user->save();

    return Redirect::home()->with('success', 'User created!');
});

License

MIT

Comments
  • Unique_with does not work??

    Unique_with does not work??

    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.

    question 
    opened by CrixuAMG 18
  • validation message in lang

    validation message in lang

    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

    opened by ReemAliT 13
  • Problem running test on models using phpUnit

    Problem running test on models using phpUnit

    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

    opened by edsuna 13
  • Add support for Laravel 6

    Add support for Laravel 6

    Closes #110

    This PR adds support for the upcoming Laravel 6.0 release. We had to upgrade to phpspec 5 for development, because illuminate/support@^6.0 requires symfony/process@^4.2.

    opened by erikgaal 12
  • Erro to run composer update in Laravel 5.2

    Erro to run composer update in Laravel 5.2

    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

    opened by JRAVILES 10
  • L5.1 - Validation always passes

    L5.1 - Validation always passes

    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.

    opened by macmotp 9
  • Class .. not found

    Class .. not found

    Hi,

    did anything how described (using laravel 4), but it yields Class 'Felixkiss\UniqueWithValidator\UniqueWithValidatorServiceProvider' not found

    Any idea?

    Thanks and greets

    opened by ronlobo 9
  • Update issue

    Update issue

    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.

    enhancement 
    opened by psaunders 8
  • Validator Conflict

    Validator Conflict

    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?

    opened by SuperlativeEntity 7
  • uniquewith-validator compatibility with softDelete

    uniquewith-validator compatibility with softDelete

    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).

    enhancement 
    opened by rhysp 7
  • Using dot in column keys

    Using dot in column keys

    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',
    ];
    
    opened by webysther 6
  • Compatibility Issue with laravel 9 php 8.X

    Compatibility Issue with laravel 9 php 8.X

    composer install throws Problem 1 - felixkiss/uniquewith-validator[3.4.0, ..., 3.4.1] require php ^7.1.3 -> your php version (8.0.13) does not satisfy that requirement. - felixkiss/uniquewith-validator 3.4.2 requires illuminate/support ^5.5|^6.0|^7.0|^8.0 -> found illuminate/support[v5.5.0, ..., 5.8.x-dev, v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require. - Root composer.json requires felixkiss/uniquewith-validator ^3.4 -> satisfiable by felixkiss/uniquewith-validator[3.4.0, 3.4.1, 3.4.2].

    You can also try re-running composer require with an explicit version constraint, e.g. "composer require felixkiss/uniquewith-validator:*" to figure out if any version is installable, or "composer require felixkiss/uniquewith-validator:^2.1" if you know which you need.

    opened by suleodu 9
  • Laravel 9.x Compatibility

    Laravel 9.x Compatibility

    This is an automated pull request from Shift to update your package code and dependencies to be compatible with Laravel 9.x.

    Before merging, you need to:

    • Checkout the l9-compatibility branch
    • Review all comments for additional changes
    • Thoroughly test your package

    If you do find an issue, please report it by commenting on this PR to help improve future automation.

    opened by laravel-shift 1
  • Using that validation rule with renamed fileds

    Using that validation rule with renamed fileds

    Hello i can't use that validation plugin "unique_with" when I have different fields from those on my database. For example in my database table I have: account_id and code_name but in my html form I have two fields to fil in so I named them to account, tb1 and in the other side I choose account2 and code_name. ==> I must validate each couple of these using unique_with rule. The problem is in the different fields name from the database. Please I'm blocked from fexw days and I need a help. Thanks a lot for your time

    opened by fatenfalfoul 0
Owner
Felix Kiss
Felix Kiss
Lightweight and feature-rich PHP validation and filtering library. Support scene grouping, pre-filtering, array checking, custom validators, custom messages. 轻量且功能丰富的PHP验证、过滤库。支持场景分组,前置过滤,数组检查,自定义验证器,自定义消息。

PHP Validate 一个简洁小巧且功能完善的php验证、过滤库。 简单方便,支持添加自定义验证器 支持前置验证检查, 自定义如何判断非空 支持将规则按场景进行分组设置。或者部分验证 支持在进行验证前对值使用过滤器进行净化过滤内置过滤器 支持在进行验证前置处理和后置处理独立验证处理 支持自定义每

Inhere 246 Jan 5, 2023
A powerful schema validator!

MetaYaml A [put your file type here] schema validator using [put another file type here] files. At the moment, file type can be Json, Yaml, or XML. It

Romaric Drigon 100 Sep 28, 2022
Argentinian CUIT and CUIL Validator

CUIT/CUIL Validator Argentinian CUIT and CUIL Rules for laravel validation Installation $ composer require iutrace/laravel-cuit-validator Usage Exampl

iutrace 6 Sep 20, 2022
MetaYaml - A powerful schema validator

MetaYaml A [put your file type here] schema validator using [put another file type here] files. At the moment, file type can be Json, Yaml, or XML. It

Romaric Drigon 100 Sep 28, 2022
PHP Email address validator - A library for validating emails against several RFC.

EmailValidator A library for validating emails against several RFC. Supported RFCs This library aims to support RFCs: 5321, 5322, 6530, 6531, 6532, 10

Eduardo Gulias Davis 10.7k Jun 13, 2022
Modern PHP validator on steroids for validating forms and/or array's.

Modern PHP Validator - Standalone Validation on Steroids Introduction Head first example Installation Adding fields for validation Execute validation

Kris Kuiper 5 Oct 5, 2022
Laravel quickly creates a verification code tool similar to Google verification code

laravel-gridCaptcha Laravel quickly creates a verification code tool similar to Google verification code laravel 快速创建一个类似于 Google 点图验证码的本地验证码扩展 介绍 lar

delete DB Flee 14 Mar 1, 2022
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

?? Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

Jordan Hall 85 Apr 26, 2022
高性能的验证器组件(Validation),适用于 Hyperf 或 Laravel 框架,可获得数百倍的性能提升

验证器 简介 兼容 Hyperf/Laravel Validation 规则 部分场景可获得约 500 倍性能提升 验证器可多次复用不同数据,无状态设计 规则可全局复用 智能合并验证规则 安装 环境要求 PHP >= 8.0 mbstring 扩展 ctype 扩展 安装命令 composer re

KK集团 80 Dec 9, 2022
Extension for the Laravel validation class

Intervention Validation Intervention Validation is an extension library for Laravel's own validation system. The package adds rules to validate data l

null 370 Dec 30, 2022
Extra validation rules for dealing with images in Laravel 5.

Image-Validator Extra validation rules for dealing with images in Laravel 5. NOTE: As of Laravel version 5.2, there are now built-in validation rules

Colin Viebrock 223 Jun 16, 2022
Laravel Validation Service

Laravel Validation Service Installation Add "prettus/laravel-repository": "1.1.*" to composer.json "prettus/laravel-validation": "1.1.*" Create a vali

Anderson Andrade 398 Nov 25, 2022
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

?? Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

Jordan Hall 85 Apr 26, 2022
A re-write of rakit/validation, a standalone validation library inspired by Laravel Validation

Somnambulist Validation This is a re-write of rakit/validation, a standalone validator like Laravel Validation. In keeping with rakit/validation, this

Somnambulist Tech 18 Dec 14, 2022
laminas-password-validator provides a validator for character-set based input validation.

laminas-password-validator laminas-password-validator provides a validator for character-set based input validation. Installation composer require pra

null 1 Mar 8, 2022
Silverstripe-searchable - Adds to the default Silverstripe search by adding a custom results controller and allowing properly adding custom data objects and custom fields for searching

SilverStripe Searchable Module UPDATE - Full Text Search This module now uses Full Text Support for MySQL/MariaDB databases in version 3.* Adds more c

ilateral 13 Apr 14, 2022
This is a visitor management system, developed by the use of Laravel 8 combined with Jetstream, Livewire and Tailwind CSS.

This is a visitor management system, developed by the use of Laravel 8 combined with Jetstream, Livewire and Tailwind CSS.

Marios Tsouras 0 Apr 23, 2022
Mobile_Detect is a lightweight PHP class for detecting mobile devices (including tablets). It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment.

Motto: "Every business should have a detection script to detect mobile readers." About Mobile Detect is a lightweight PHP class for detecting mobile d

Şerban Ghiţă 10.2k Jan 4, 2023
The game is implemented as an example of scalable and high load architecture combined with modern software development practices

Crossword game The game is implemented as an example of scalable and high load architecture combined with modern software development practices Exampl

Roman 56 Oct 27, 2022
An advanced yet user-friendly content management system, based on the full stack Symfony framework combined with a whole host of community bundles

An advanced yet user-friendly content management system, based on the full stack Symfony framework combined with a whole host of community bundles. It provides a full featured, multi-language CMS system with an innovative page and form assembling process, versioning, workflow, translation and media managers and much more.

Kunstmaan | Accenture Interactive 374 Dec 23, 2022