meYnot
meYnot

Reputation: 342

Laravel validation for exists except zero not nullable

In categories table I have the following columns id, parent_id, title

Now, parent_id is the parent category for sub-category, but for the root/primary categories parent_id is 0 because they have no parent!

<?php
'parent_id'=>'required|exists:categories,id|nullable' 
// wont work, because parent_id = 0

I used also [sometimes] with no luck!

Upvotes: 0

Views: 3680

Answers (1)

Matteo Meil
Matteo Meil

Reputation: 1353

I think your problem is within exists. From Laravel 5.8 exists' docs

The field under validation must exist on a given database table

Applied to your case: you are requesting that the field under validation must have a value that matches an existing id in categories table and you're asserting

for the root/primary categories parent_id is 0 because they have no parent

and if they have no parent their parent_id won't match any id in categories table.

Note also that required and nullable shouldn't be on the same validation field: from required rule's docs

The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true:

  • The value is null.
  • ...

and from nullable rule's docs

The field under validation may be null.

So, you are requesting that the field is not empty, but you are allowing null value, that's denied from required validation rule.

At the end, to solve your problem you have to do:

[
    'parent_id' => 'exists:categories,id|nullable'
]

and set NULL on root categories, or use

[
    'parent_id' => 'required'
]

and manually check that parent_id exists in your database except for root categories that will have 0

Side note:
To be sure that you're inserting existing ids in your parent_id field, I would suggest you to add a foreign key constraint and set NULL on root categories:

Schema::create('categories', function (Blueprint $table) {
    $table->bigIncrements('id');

    // other definitions...

    $table->unsignedBigInteger('parent_id')->nullable();

    $table->foreign('parent_id')->references('id')->on('categories');
});

Upvotes: 2

Related Questions