How to change the value of an input type text to a date format in Laravel

Asked

Viewed 249 times

0

The problem is that the input type text is sending the date value to the Mysql Database in the following format DD/MM/YYYY, but Mysql only accepts a text for the date format if it is in the following format YYYY-MM-DD or YYYYMMDD.

Code of my input:

<input class="form-control datepicker form-control-alternative{{ $errors->has('birth_date') ? ' is-invalid' : '' }}" name="birth_date" id="input-birth_date" placeholder="Informe sua data de nascimento" type="text" value="{{ old('birth_date') }}" required autofocus>

Code of variable in person function:

    protected $fillable = [
    'birth_date',
];

Thanks in advance!

1 answer

0


Good afternoon, you can set the input type to date

<input type="date" class="form-control datepicker form-control-alternative{{ $errors->has('birth_date') ? ' is-invalid' : '' }}" name="birth_date" id="input-birth_date" value="{{ old('birth_date') }}" required autofocus/>

If you do not want this way, in the validator you can put the validator
date_format (date_format:Y-m-d) and then do a manual date formatting (use boot to automate).

Within your model you can try to do so

public static function boot() {
    parent::boot();

    static::creating(function (AccountCreation $item) {
        $date = date_create($item->birth_date); 
        $item->birth_date = date_format($date, 'Y-m-d H:i:s');
    });
}

Reference: https://laravel.com/docs/5.5/validation#Rule-date-format https://www.w3schools.com/tags/att_input_type_date.asp https://stackoverflow.com/questions/50287823/validating-a-custom-date-format-in-with-laravel-validator https://stackoverflow.com/questions/35907641/laravel-model-boot-creating-not-firing

  • The following error is presented to me: Argument 1 passed to App\People::App\{closure}() must be an instance of App\AccountCreation, instance of App\People given, called in C:\wamp64\www\SIGASS\vendor\laravel\framework\src\Illuminate\Events\Dispatcher.php on line 347

  • 1

    Accountcreation -> put your model’s class!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.