Search code examples
codeigniterdateformatentitycodeigniter-4

Entity saving to database wrong date format codeigniter 4


My entity looks like this:

class Request extends Entity
{
    protected $casts = [
        'id'                => 'integer',
        'added_at'          => 'datetime',
        'deadline'          => 'datetime',
        'completed'         => 'integer'
    ]; 
}

When saving, the model generates the date fields in 'Y/m/d' format for the sql query, hovewer my database can not parse this. How can I force it to generate dates in 'Y-m-d' format when calling $myModel->insert($myEntity) ?


Solution

  • Entities has the option of setters. It performs the validation or conversion in your case whenever you perform save an entity. Lets say you want to change the form of deadline in that case you have to set the Setter for your deadline as follow :

    public function setDeadline(string $dateString)
    {
        $this->attributes['deadline'] = $dateString;
    
        return $this;
    }
    

    In the following line : $this->attributes['deadline'] = $dateString; You will use some library like Carbon to format the $dateString and then reassign your variable deadline. Reference link : https://codeigniter4.github.io/userguide/models/entities.html