Set default database connection of a validator #38377
-
I have a validator with a complex dynamically generated rules. I want to set default database connection for this validator to be used for the $verifier = App::make('validation.presence');
$verifier->setConnection('sqlite');
$validator = Validator::make($request->data, $rules);
$validator->setPresenceVerifier($verifier);
$data = $validator->validate(); // always uses the default app DB connection not the specified one 'sqlite' But is doesn't work and uses the app's default database connection instead. I sent a PR #38331 to fix this but closed, I realized that it won't work as expected if one of the rules has specified a specific connection on it self (the example below won't work with this PR). Then, I sent another PR #38358 to add $validator = Validator::make($request->data, [
'state' => 'exists:states', // uses 'sqlite.states'
'email' => 'exists:connection.staff' // uses 'connection.staff'
]);
$validator->setConnection('sqlite'); But this PR is closed too:
My rules are not static to simply add connection name to each rule, any suggestion? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You may do this by defining a custom validator: namespace App\Classes;
use Illuminate\Validation\Validator as BaseValidator;
class Validator extends BaseValidator
{
/**
* Get the Presence Verifier implementation.
*
* @param string|null $connection
* @return \Illuminate\Validation\PresenceVerifierInterface
*
* @throws \RuntimeException
*/
public function getPresenceVerifier($connection = null)
{
return tap(parent::getPresenceVerifier($connection), function ($verifier) {
$verifier->setConnection('sqlite');
});
}
} and use it: $factory = App::make('validator');
$factory->resolver(function (...$args) {
return new \App\Classes\Validator(...$args);
});
$validator = $factory->make($request->data, $rules); |
Beta Was this translation helpful? Give feedback.
You may do this by defining a custom validator:
and use it: