CodeIgniter Forums

Full Version: I can't get the $beforeInsert and $beforeUpdate model events to work for me
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I have problems getting the model events to activate the callback to the hash my password before inserting data into the database or updating the database

PHP Code:
<?php

namespace Modules\Uauth\Controllers;


use 
Modules\Uauth\Models\UauthModel;
use 
CodeIgniter\Controller;

class 
Signup extends Controller {

   
    
public function create() {
        if ($this->request->getMethod() === 'post') {
            $validation $this->holder['validation'];
            $session $this->holder['session'];

            // echo '<pre>' . \var_export($this->validation->withRequest($this->request)->run(), true) . '</pre>';
            if (! $validation->withRequest($this->request)->run()) {
                // fails
                $data = [
                    'page_title' => 'Sign up',
                    'validation' => $validation,
                    'session'    => $session,
                ];

                $session->setFlashdata('register_fail''Form Error Found');
                return view($this->_path 'register'$data);
            } else {
                // Passess
                $model = new UauthModel();

                $dx['data'] = [
                    'last_name' => $this->request->getVar('lastname'),
                    'first_name' => $this->request->getVar('firstname'),
                    'gender' => $this->request->getVar('gender'),
                    'country' => $this->request->getVar('nation'),
                    'email' => $this->request->getVar('email'),
                    'username' => $this->request->getVar('username'),
                    'password' => $this->request->getVar('password'),
                ];

                $model->create($dx);

                
            
}
            
        
} else {
            return redirect()->to('/signup');
        }
        
    
}

}


<?
php

namespace Modules
\Uauth\Models;

/**
 * --------------------------------------------------------------------
 * Log in Module Model
 * --------------------------------------------------------------------
 */

use CodeIgniter\Model;

class UauthModel extends Model {

    protected $table = 'users';

    protected $returnType = 'object';

    protected $allowedFields = ['last_name', 'first_name', 'gender', 'country', 'email', 'username', 'password_hash'];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = '';

    protected $beforeInsert = ['hashPassword'];
    protected $afterInsert = ['hashPassword'];
    protected $beforeUpdate = ['hashPassword'];

    private $_db, $_builder;

    public function __construct() {
        $this->_db = \Config\Database::connect();

        $this->_builder = $this->_db->table($this->table);
    }

    public function create($data) {
        
        $this
->insert($data['data']);
    }

    public function get_user_by_email($email) {
        return $this->_builder->where('email', $email)->countAllResults();
    }

    protected function hashPassword(array $data) {
        if (! isset($data['data']['password']) ) return $data;

        $data['data']['password_hash'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
        unset($data['data']['password']);
        
        return $data
;
    }
    
}



how do i get the callback hashPassword to work 
(06-04-2020, 10:08 AM)oghenemavo Wrote: [ -> ]Hi, I have problems getting the model events to activate the callback to the hash my password before inserting data into the database or updating the database

PHP Code:
<?php

namespace Modules\Uauth\Controllers;


use 
Modules\Uauth\Models\UauthModel;
use 
CodeIgniter\Controller;

class 
Signup extends Controller {

   
    
public function create() {
        if ($this->request->getMethod() === 'post') {
            $validation $this->holder['validation'];
            $session $this->holder['session'];

            // echo '<pre>' . \var_export($this->validation->withRequest($this->request)->run(), true) . '</pre>';
            if (! $validation->withRequest($this->request)->run()) {
                // fails
                $data = [
                    'page_title' => 'Sign up',
                    'validation' => $validation,
                    'session'    => $session,
                ];

                $session->setFlashdata('register_fail''Form Error Found');
                return view($this->_path 'register'$data);
            } else {
                // Passess
                $model = new UauthModel();

                $dx['data'] = [
                    'last_name' => $this->request->getVar('lastname'),
                    'first_name' => $this->request->getVar('firstname'),
                    'gender' => $this->request->getVar('gender'),
                    'country' => $this->request->getVar('nation'),
                    'email' => $this->request->getVar('email'),
                    'username' => $this->request->getVar('username'),
                    'password' => $this->request->getVar('password'),
                ];

                $model->create($dx);

                
            
}
            
        
} else {
            return redirect()->to('/signup');
        }
        
    
}

}


<?
php

namespace Modules
\Uauth\Models;

/**
 * --------------------------------------------------------------------
 * Log in Module Model
 * --------------------------------------------------------------------
 */

use CodeIgniter\Model;

class UauthModel extends Model {

    protected $table = 'users';

    protected $returnType = 'object';

    protected $allowedFields = ['last_name', 'first_name', 'gender', 'country', 'email', 'username', 'password_hash'];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = '';

    protected $beforeInsert = ['hashPassword'];
    protected $afterInsert = ['hashPassword'];
    protected $beforeUpdate = ['hashPassword'];

    private $_db, $_builder;

    public function __construct() {
        $this->_db = \Config\Database::connect();

        $this->_builder = $this->_db->table($this->table);
    }

    public function create($data) {
        
        $this
->insert($data['data']);
    }

    public function get_user_by_email($email) {
        return $this->_builder->where('email', $email)->countAllResults();
    }

    protected function hashPassword(array $data) {
        if (! isset($data['data']['password']) ) return $data;

        $data['data']['password_hash'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
        unset($data['data']['password']);
        
        return $data
;
    }
    
}



how do i get the callback hashPassword to work 

My code is very similar to your and it works for me:
PHP Code:
protected function hashPassword(array $data) {
        if(isset($data['data']['password']))
            $data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
        return $data;
    

Instead of unsetting the unhashed password, my code overwrites it with the newly hashed password. Also, I noticed you are saving the hashed password at 'password_hash' and not 'password'.  Is that the name of the column in your database?