Eloquent Validation for composite unique key

半世苍凉 提交于 2020-01-03 05:46:04

问题


I'm using Eloquent outside laravel framework from https://github.com/illuminate/database. The below is my composer file

{
    "require": {
        "illuminate/database": "*",
        "illuminate/validation": "*",
        "dhorrigan/capsule": "*"
    }
}

And because of problem in Validator::make(). I'm using one of the suggested method in stackoverflow to use it like

class Validator
{

    protected static $factory;

    public static function instance()
    {
        if (!static::$factory) {
            $translator = new Symfony\Component\Translation\Translator('en');
            static::$factory = new Illuminate\Validation\Factory($translator);
        }

        return static::$factory;
    }

    public static function __callStatic($method, $args)
    {

        $instance = static::instance();

        return call_user_func_array(array($instance, $method), $args);

    }
}

Now i can validate required, in, etc. But i'm not able to validate unique key index for two or three columns. I tried the https://github.com/felixkiss/uniquewith-validator. But its extended from Validator. It dint work for me. And i'm not sure if laravel has a way to handle validation for composite unique keys. Their examples are not clear in the documentation.

Can you suggest a way to solve the composite unique key validation ?


回答1:


In my case some rules (e.g.: unique) didn't work since you need a presenceValidator set in your factory. I managed it and this is my approach:

Create your own class (MyModel) extending Eloquent model and add this method:

public static function getResolver()
    {
        return parent::$resolver;
    }

in your validator class after namespace (easier names):

use \Illuminate\Validation\Factory as Factory;

use \Illuminate\Validation\DatabasePresenceVerifier as DatabasePresenceVerifier;

use \Symfony\Component\Translation\Translator as Translator;

Finally (I'm not using dhorrigan capsule but it may work):

$translator = new Translator('en');
$container = $capsule->getContainer();            
$presenceVerifier = new DatabasePresenceVerifier(MyModel::getResolver());
static::$factory = new Factory($translator, $container);
static::$factory->setPresenceVerifier($presenceVerifier);

Now you can use unique validation rule and other rules based on DB.

Hope it helps!



来源:https://stackoverflow.com/questions/18781555/eloquent-validation-for-composite-unique-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!