Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Database in Validator in Laravel

I want to Validate requested values from controller action by this way:

    // 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);

All is fine if I'm using the default database, but for this Validation I need to check the tables in other database. In config I have two databases:

    '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'    => '',
    ),
),

When I call the Validation, it is checking by "unique" rule in my default database so I need to change it, but I cannot found anywhere how to do this.

like image 598
Narkon Avatar asked Dec 07 '14 11:12

Narkon


2 Answers

I made it by this way:

    $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);

Solution for others who had this problem.

like image 143
Narkon Avatar answered Oct 02 '22 07:10

Narkon


You can set the connection name before the table name as shown below.

$rules = array(
'username'        => 'required|min:5|unique:server_auth.users,username',  
'email'           => 'required|email|unique:server_auth.users,email',  
'password'        => 'required|min:8',
);
like image 28
Mathurankan Kanesalingam Avatar answered Oct 02 '22 09:10

Mathurankan Kanesalingam