Welcome Guest, Not a member yet? Register   Sign In
updated_at field is not working
#1

Hi there, i tried all this methods posted here and googled out but found nothing useful.
The wierd thing is 'created_at' is working but 'updated_at' gets a null value 
so here is my model
PHP Code:
<?php

namespace App\Models;

use 
CodeIgniter\Model;

class 
UserModel extends Model
{
    protected $DBGroup          'default';
    protected $table            'users';
    protected $primaryKey      'id';
    protected $useAutoIncrement true;
    protected $insertID        0;
    protected $returnType      'array';
    protected $useSoftDeletes  false;
    protected $protectFields    true;
    protected $allowedFields    = ['firstname''lastname''email''password''updated_at'];
    protected $dateFormat 'datetime';

    // Callbacks
    protected $allowCallbacks true;
    protected $beforeInsert  = ['beforeInsert'];
    protected $beforeUpdate  = ['beforeUpdate'];

      protected function beforeInsert(array $data){
          $data $this->passwordHash($data);
          $data['data']['created_at'] = date('Y-m-d H:i:s');      
          
return $data;
        }
      
      
protected function beforeUpdate(array $data){
        $data $this->passwordHash($data);
        $data['data']['updated_at'] = date('Y-m-d H:i:s');      
        
return $data;
        }

      protected function passwordHash(array $data)
      {
          if(isset($data['data']['password']))
          {
              $data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
          }
          return $data;
      }



Code:
Here is my controller
PHP Code:
<?php

namespace App\Controllers;

use 
App\Models\UserModel;

class 
Home extends BaseController
{
    public function index()
    {
        $data = [];
        echo view('template/header'$data);
        echo view('login');
        echo view('template/footer');
    }

    public function register()
    {
        $data = [];

        if($this->request->getMethod() == 'post')
        {
            //Validações
            $rules = [
                'firstName' => ['label' => 'Primeiro Nome''rules' => 'required|min_length[3]|max_length[20]|trim'],
                'lastName' => ['label' => 'Ultimo Nome''rules' => 'required|min_length[3]|max_length[20]|trim'],
                'email' => ['label' => 'Email''rules' => 'valid_email|required|min_length[6]|max_length[50]|is_unique[users.email]|trim'],
                'password' => ['label' => 'Senha''rules' => 'required|min_length[3]|max_length[255]'],
                'confirmPassword' => ['label' => 'Confirme a Senha''rules' => 'required|matches[password]']
            ];

            if(!$this->validate($rules))
            {
                $data['validation'] = $this->validator;
            } else{
                //Insere o usuário no BD
                $model = new UserModel();

                $newData = [
                    'firstname' => $this->request->getVar('firstName'),
                    'lastname' => $this->request->getVar('lastName'),
                    'email' => $this->request->getVar('email'),
                    'password' => $this->request->getVar('password')
                ];
                $model->save($newData);
                $session session();
                $session->setFlashdata('success''Registro efetuado com sucesso!');
                return redirect()->to('/');
            }
        }

        echo view('template/header'$data);
        echo view('register');
        echo view('template/footer');
    }

Code:
and here is my DB

Code:
DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `firstname` varchar(50) NOT NULL,
  `lastname` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;


Thanks in advance.
Reply
#2

(This post was last modified: 04-01-2022, 03:39 AM by iRedds.)

1. Timestamps are set automatically if configured correctly. There is no point in events.
2. If the data does not have a primary key when using the Model::save() method, then it will be considered that this is a new record and, accordingly, update events will not be called.
Reply
#3

i just setted up $useTimestamps to true and its working fine
 
See the documentation
Reply




Theme © iAndrew 2016 - Forum software by © MyBB