Code Monkey home page Code Monkey logo

uniquewith-validator's Introduction

unique_with Validator Rule For Laravel

Join the chat at https://gitter.im/felixkiss/uniquewith-validator

Build Status

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

Installation

Install the package through Composer.

Laravel 4

On the command line:

composer require felixkiss/uniquewith-validator:1.*

Laravel 5

On the command line:

composer require felixkiss/uniquewith-validator:2.*

Configuration

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

'providers' => array(
    // ...

    'Felixkiss\UniqueWithValidator\UniqueWithValidatorServiceProvider',
),

Usage

Use it like any Validator rule:

$rules = array(
    '<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 = array(
    'first_name' => 'unique_with:users, middle_name, last_name = sur_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(array('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 = array(
        '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!');
});

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

This will ignore row with id 2

$rules = array(
    '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 = array(
    'first_name' => 'required|unique_with:users,last_name,2 = custom_id_column',
    'last_name' => 'required',
);

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 = array(
    'first_name' => 'required|unique_with:users,last_name,deleted_at,2 = custom_id_column',
    'last_name' => 'required',
);

Extending the Laravel Validator

For simple validation rules that don't need translator or custom messages:

Validator::extend('foo_bar', function($attribute, $value, $parameters)
{
    return ($attribute == 'foo' && $value == 'bar');
});

For more sophisticated rules:

class CustomValidator extends Felixkiss\UniqueWithValidator\ValidatorExtension
{
    public function validateOnlyApple($attribute, $value, $parameters)
    {
        // $this->translator, $this->messages, etc. available
        return ($attribute == 'company' && $value == 'apple');
    }
}

Validator::resolver(function($translator, $data, $rules, $messages)
{
    return new CustomValidator($translator, $data, $rules, $messages);
});

License

MIT

uniquewith-validator's People

Contributors

alexmgarcia avatar benesch avatar damianopetrungaro avatar felixkiss avatar gitter-badger avatar jdunk avatar lbausch avatar redgluten avatar redidsoft avatar reemalit avatar roelvanmeer avatar salihklc avatar tieskedh avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.