Framework: Switching the Database Connection used by Validator

Created on 10 May 2013  路  7Comments  路  Source: laravel/framework

I have multiple databases used by my application and found myself needing to validate against the non-default connection. The problem was that the Validator class doesn't provide a way to switch the connection; it needs to be done in DatabasePresenceVerifier.

The DatabasePresenceVerifier is available through Validator but it is protected so I needed to extend the Validator Class and add this function that would allow passing the name of the connection to the object returned by Validator::make().

    public function setConnection($connection)
    {
        $this->presenceVerifier->setConnection($connection);
    }

This was easy enough because of the built in resolver, but it took me a little while to figure out.

Should this be doable without extending the class? Or did I miss some glaringly obvious way to do this.

Most helpful comment

'email' => 'unique:connection.users,email_address'

See: https://laravel.com/docs/5.1/validation

All 7 comments

Validator::getPresenceVerifier()->setConnection($connection);

Err... should be $validator->getPresenceVerifier()... not a static call like I posted above.

Awesome. Thank you.

Where would you put that line in your application?

In the model?

WMeldon. Can you please share how you implemented this?

@dmi3000 After Validator::make() but before you run it. I did this in the repositories that wrapped my models but wherever you're doing validation will work.

How would you do this for form request validation?

'email' => 'unique:connection.users,email_address'

See: https://laravel.com/docs/5.1/validation

Was this page helpful?
0 / 5 - 0 ratings

Related issues

CupOfTea696 picture CupOfTea696  路  3Comments

felixsanz picture felixsanz  路  3Comments

lzp819739483 picture lzp819739483  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments

Fuzzyma picture Fuzzyma  路  3Comments