slewis's avatar

Laravel extend Validator to account for different schemas/connections

Hi, Currently we are using the Laravel's form request validation to verify that a user's email is unique to the users table:

'email' => 'required|email|unique:pgsql.schema.users'

We are using postgres and in order to connect to the appropriate schema we need to define the connection name as follows in the unique rule:

unique:[connection].[schema].[table]

We cannot leave out [connection], because then Laravel will assume the [schema] as the connection name, as described here: https://laracasts.com/discuss/channels/laravel/controllervalidate-unique-specify-postgres-schema

However, our test kit which utilizes sqlite will have a different connection and no concept of schemas. I'm wondering where the best place is to override Laravel's Unique Validator to read the current environment and prefix the db name/schema to the unique rule so the form request rule can simply be:

'email' => 'required|email|unique:users'

but in reality it will behave like:

LIVE env 'email' => 'required|email|unique:pgsql.schema.users' TEST env 'email' => 'required|email|unique:users' (unchanged)

0 likes
2 replies
bobbybouwmann's avatar

In my opinion you are trying to cover up a issue instead of fixing the issue.

I think your test environment should be the same as your local/production environment. So if you use postgres on your local/production environment why not use postgres for testing as well?

slewis's avatar

@bobbybouwmann I agree that would be ideal, but would we not run into the same issue if we wanted to use a different DB for local/prod vs testing?

prod: 'email' => 'unique:pgsql_prod.schema.users'

test 'email' => 'unique:pgsql_test.schema.users'

Part of the problem is having to define the connection name in the rule when using Postgres schemas, and it therefore needs to be dynamic.

This is a slight tangent, but It seems like the trouble lies in the fact that the connection and schema delimiters are the same. Using separate delimiters could allow us to simply just use the default/current connection when not defined.

example: 'email' => 'unique:[connection]@schema.users'

Please or to participate in this conversation.