Welcome Guest, Not a member yet? Register   Sign In
Validation: in_db[table.field]
#5

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

I share my code...

app/Libraries/Rules.php
PHP Code:
<?php

namespace App\Validation;

use 
Config\Database;

class 
Rules
{
    /**
     * 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
        
sscanf($field'%[^.].%[^.]'$table$field);

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

        
$row $db->table($table)
                
  ->select('1')
                
  ->where($field$str)
                
  ->limit(1);

        if (
$row->get()->getRow() !== null)
        {
            return 
true;
        }

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


app/Config/Validation.php
PHP Code:
(...)
    public 
$ruleSets = [
        (...)
        \
App\Validation\Rules::class,
    ];
(...) 
Reply


Messages In This Thread
Validation: in_db[table.field] - by thingNumber1 - 10-27-2019, 12:26 PM
RE: Validation: in_db[table.field] - by MGatner - 11-01-2019, 05:55 AM
Solución - by thingNumber1 - 11-08-2019, 03:07 PM
RE: Validation: in_db[table.field] - by Ale - 01-20-2020, 03:33 PM



Theme © iAndrew 2016 - Forum software by © MyBB