如何在Laravel中的Validator中更改数据库

时间:2014-12-07 11:20:11

标签: php laravel laravel-4

我想通过这种方式验证来自控制器操作的请求值:

    // validate the info, create rules for the inputs
    $rules = array(
        'username'        => 'required|min:5|unique:users,username',
        'email'           => 'required|email|unique:users,email',
        'password'        => 'required|min:8',
    );

    // run the validation rules on the inputs from the form
    $validator = Validator::make(Input::all(), $rules);

如果我使用默认数据库,一切都很好,但对于此验证,我需要检查其他数据库中的表。在配置中,我有两个数据库:

    'connections' => array(

    'main' => array(
        'driver'    => 'mysql',
        'host'      => '*******',
        'database'  => '*******',
        'username'  => '*******',
        'password'  => '*******',
        'charset'   => 'utf8',
        'collation' => 'utf8_general_ci',
        'prefix'    => 'ko_',
    ),

    'server_auth' => array(
        'driver'    => 'mysql',
        'host'      => '*******',
        'database'  => '*******',
        'username'  => '*******',
        'password'  => '*******',
        'charset'   => 'utf8',
        'collation' => 'utf8_general_ci',
        'prefix'    => '',
    ),
),

当我调用验证时,它正在我的默认数据库中通过“唯一”规则进行检查,因此我需要更改它,但我无法在任何地方找到如何执行此操作。

2 个答案:

答案 0 :(得分:9)

我这样做了:

    $verifier = App::make('validation.presence');
    $verifier->setConnection('server_auth');

    // validate the info, create rules for the inputs
    $rules = User::$rules = array(
        'username'        => 'required|min:5|unique:users,username',
        'email'           => 'required|email|unique:users,email',
        'password'        => 'required|min:8',
    );

    // run the validation rules on the inputs from the form
    $validator = Validator::make(Input::all(), $rules);

    $validator->setPresenceVerifier($verifier);

解决有此问题的其他人。

答案 1 :(得分:0)

您可以在表名之前设置连接名,如下所示。

$rules = array(
'username'        => 'required|min:5|unique:server_auth.users,username',  
'email'           => 'required|email|unique:server_auth.users,email',  
'password'        => 'required|min:8',
);