DEV Community

loading...

Laravel validation rule — doesn’t exist

mattkingshott profile image Matt Kingshott 👨🏻‍💻 Originally published at Medium on ・2 min read

Image courtesy of Unsplash

Laravel validation rule — doesn’t exist

In this new series, we’ll be exploring the concept of custom validation rules in Laravel and how they can assist you. I’m posting an article each day with a new rule you can use in your projects. The rules are also part of a package.

In this post, we’ll be creating a rule which serves as the opposite to Laravel’s native database exists rule. The rule will ensure that a record does not exist.

If you’re new to this topic, check out the first article in the series.

Promotion

I’ve recently released Pulse — a friendly, affordable server and site monitoring service designed specifically for developers. It includes all the usual hardware monitors, custom service monitors, alerting via various notification channels, logs, as well as full API support. Take a look… https://pulse.alphametric.co

Server and Site Monitoring with Pulse

The check and response

Let’s begin by writing the logic necessary to ensure that the database record does not exist. To do so, our rule will need to accept a database table and a record column to verify against. In that respect, our rule is very similar to the RecordOwner rule we created earlier:

public function passes($attribute, $value)
{
    return DB::table($this->parameters[0])
             ->where($this->parameters[1], $value)
             ->doesntExist();
}

Next, we’ll need to write an error message to respond with when the user has supplied a value that already exists:

public function message()
{
    return 'The :attribute already exists';
}

Testing it works

As before, we’ll write a quick unit test to confirm that the rule works correctly and rejects values that already exist in the database:

/\*\* @test \*/
public function a\_does\_not\_exist\_rule\_can\_be\_validated()
{
    $rule = ['user\_id' => [new App\Rules\DoesNotExist('users', 'id')]];

    $user = factory(App\User::class, 1)->create();

    $this->assertTrue(validator(['user\_id' => 'non\_existent\_user'], $rule)->passes());

    $this->assertFalse(validator(['user\_id' => $user->id], $rule)->passes());
}

Wrapping Up

You can see the complete class and pull it into your projects by visiting the repo on Github: https://github.com/alphametric/laravel-validation-rules

I have additional validation rules that I intend to share with you in the coming days, so be sure to follow me for those articles. If you’re interested, you can also follow me on Twitter to see everything I’m up to.

Happy coding!

Discussion

pic
Editor guide