0

I'm looking for a DateTime Mutator that change the format of dates, I'm working with Oracle DB and the admitted Format is (DD/MM/YYYY) and the input type "date" stores dates in (YYYY,MM,DD) format.

I found the $date function and a trait by Torzer, but I have to indicate the fields that I want to convert the format.

is there some trait or function that detect all date fields and convert them automatically in a format (DD/MM/YYYY)? this without indicate the field.

nowadays I use protected $date in my model:

protected $dates = [ 'fecha_nac', 'fecha_nac1', 'fecha_nac2', ];
1
  • What's wrong with specifically defining the date fields on the model yourself? Commented Sep 10, 2018 at 18:14

2 Answers 2

1

By default laravel uses date formate 'Y-m-d H:i:s' if you want to use a different format you can customize it in your model in the following way.

    protected $dateFormat = 'your date formate';

in your case it will be.

    protected $dateFormat = 'd-m-Y';
Sign up to request clarification or add additional context in comments.

Comments

0

You can override the getDates method on HasAttributes trait.

/**
 * Get the attributes that should be converted to dates.
 *
 * @return array
 */
public function getDates()
{
    $defaults = [static::CREATED_AT, static::UPDATED_AT];

    return $this->usesTimestamps()
                ? array_unique(array_merge($this->dates, $defaults))
                : $this->dates;
}

On your model:

public function getDates()
{
    $dates = parent::getDates();

    // add your dynamic logic here

    return $dates;
}

I would really go for explicitly defining which fields should be converted as these dynamic operations can be expensive if you are working with the model quite a lot.

2 Comments

Hi, but what if I have 10 models with 10 different date fields? and not two static fields. I would need to make the function for each date field?
You will either have statically defined which fields are dates on each model (which is pretty clean) using $dates property, or you can have some custom logic (lets say the date field is prefixed with d_) and override the getDates method to search for this pattern and add the field to $dates array dynamically. You can declare these properties/methods on the model without using trait btw.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.