CodeIgniter Forums
Validation: in_db[table.field] - Printable Version

+- CodeIgniter Forums (
+-- Forum: CodeIgniter 4 (
+--- Forum: CodeIgniter 4 Feature Requests (
+--- Thread: Validation: in_db[table.field] (/showthread.php?tid=74706)

Validation: in_db[table.field] - thingNumber1 - 10-27-2019

Imagine that you have a list of fruits in your database and your users need to select their favorite fruits (but it must be a fruit that previously existed in the database) ...

Currently, to validate the entry, you must select all the fruits from your database, implode the results array and put it into the validation rule with something like this: 

in_list['. Implode (',', $ result). ']'

It would be amazing if you could validate it with something like this: 


Where "fruits" is the name of the table and "id" is the name of the field.

In addition, the query for the second validation method would be faster than the first one because in the second case you can search for a primary or unique key, while in the first you must search for all the "fruits" in the database.

Note: I am aware that currently you can still validate the entry by looking for the primary key outside the validation rules ... but this is not fun if the idea of using the validation rules is to facilitate the lives of the programmers.

RE: Validation: in_db[table.field] - MGatner - 11-01-2019

How would this be different than `is_unique`?

"Checks if this field value exists in the database. Optionally set a column and value to ignore, useful when updating records to ignore itself."


RE: Validation: in_db[table.field] - thingNumber1 - 11-06-2019

Is the opposite. 

While `is_unique` returns an error message if the value exist in the DB and continues if the value does not exist. `in_db` might return the error if the values does not exists and should continue if the value exist.

I think is easier to understand if instead of `in_db` we name it `not_is_unique`.

Solución - thingNumber1 - 11-08-2019

I created the feature and here is the Pull Request.

RE: Validation: in_db[table.field] - Ale - 01-20-2020

Great request. I have the same exactly rule in my validation rules file.

I share my code...

PHP Code:

namespace App\Validation;


     * Checks the database to see if the given value exist in db table.
     * Example:
     *    in_db[table.field]
     * @param string $str
     * @param string $field
     * @param array  $data
     * @author Alejandro D. Guevara <[email protected]>
     * @return boolean
public function in_db(string $str nullstring $field, array $datastring &$error null): bool
// Break the table and field apart

$db Database::connect($data['DBGroup'] ?? null);

$row $db->table($table)

        if (
$row->get()->getRow() !== null)

$error lang('Validation.in_db', ['table' => $table]);

PHP Code:
$ruleSets = [