CodeIgniter Forums
is_unique throws error on not found field - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: is_unique throws error on not found field (/showthread.php?tid=90220)



is_unique throws error on not found field - ramonpuig - 02-23-2024

Hi!
i am trying to validate a form field , concretely the username with is_unique.

My controller has this code:
PHP Code:
if ($this->request->getMethod() === 'post') {

            
$this->validation->setRules([
                
'username' => 'required|alpha_numeric|min_length[3]|max_length[20]|is_unique[users.username]',
            
'email' => 'required|valid_email|is_unique[users.email]',
            
'password' => 'required|min_length[8]',
            ]);

                    if (!
$this->validate($this->validation->getRules()))

                        { 
The last line here goes to the is_unique function in rules.php
PHP Code:
public function is_unique(?string $strstring $field, array $data): bool
    
{
        [$field$ignoreField$ignoreValue] = array_pad(explode(','$field), 3null);

        sscanf($field'%[^.].%[^.]'$table$field);

        $row Database::connect($data['DBGroup'] ?? null)
            ->table($table)
            ->select('1')
            ->where($field$str)
            ->limit(1);

        if (! empty($ignoreField) && ! empty($ignoreValue) && ! preg_match('/^\{(\w+)\}$/'$ignoreValue)) {
            $row $row->where("{$ignoreField} !="$ignoreValue);
        }

        return $row->get()->getRow() === null;
    
The line        return $row->get()->getRow() === null;
throws this error:

Error: Call to a member function getRow() on bool

. I do not understand why this throws error since the $row ->get() returns false because it doesnt find the username field value, which is okay since the user has not been registered yet, so is_unique should return return $row->get()->getRow() === null as TRUE.

Am I missing something here?

Your help would be greatly appreciated as i am new with ci4 and so far i like it


RE: is_unique throws error on not found field - ramonpuig - 02-23-2024

I found the issue, it was a silly typo on the table name I was using users.username instead of Users.username. But the error thrown was not helpful to find it , but it kind of gave the clue. Coding in ci4 is a like a detective's job!