Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TollerHovler's avatar

Database validation vs. request validator or both?

Hiya!

What is the best (and/or common) practice for validating data inserted to the database? In my example I use the "unique" rule, but the question remains for everything else.

In the migration:

    public function up() {
        Schema::create('table', function (Blueprint $table) {
            $table->string('foo')->unique();
        });
    }

In the request class:

    public function rules() {
        return [
            'foo' => 'unique:table'
        ];
    }

Going with a TDD-approach, I was writing some tests for what may or may not be included in string foo, and after failed tests, implemented the rules in the validator. But then I got to the "unique" rule. This time the test that asserts that inserting a row where string foo already exists would fail, passed. This because - even if I did not write the rule in the validator, the row was not inserted because of the constraint set on the field in the migration.

And I am not sure if I want this to happen. This means that since the tests pass, all seems well and good without needing to implement anything in the validator. This would result in a user attempting to insert duplicate content not getting a controlled error-message, but a crash.

I'm thinking I'll just remove the unique-constraint on the migration, only validating with the validator, both to solve this issue, but also making it easier for me to add or remove rules in future versions of the application. But when learning Laravel, it seems like every teacher is doing both the constraint and the rule, so I have used the same approach, but when tests started to pass but warning-lights went on in my head I was not sure anymore.

Am I missing something obvious here?

Is there any reason I would want to have the unique-constraint on the field if I have the rule in the validator?

0 likes
1 reply
rawilk's avatar

Of course add the constraints to the database, but also use server-side validation so you can provide better feedback to the end-user.

Please or to participate in this conversation.