Problem with updating date from form to database

Viewed 101

I am trying to update date_of birth column in database and when I submit my form I get this error

DateTime::__construct(): Failed to parse time string (25/03/1995) at position 0 (2): Unexpected character

Now in my blade I formated date of birth to show d/m/Y and when updating I think it updates Y/m/d, because when I remove format function from my blade it works fine. So I need help on how to update with format('d/m/Y') in my database and how to validate it properly in my form request validation. Any help is appreciated. Here is my code.

index.blade.php

<input type="text" placeholder="dd/mm/yyyy" name="date_of_birth" value="{{ $userForShowProfile->date_of_birth ? $userForShowProfile->date_of_birth->format('d/m/Y') : "" }}">

UserController.php

public function updateProfileCharacteristics(UpdateProfileCharacteristicsRequest $request)
{
     $user = Auth::user();

     $user->update(
     [
        'date_of_birth' => $request->date_of_birth,
        'age' => Carbon::now()->diffInYears($request->date_of_birth),
        'updated_at' =>  Carbon::now()
     ]
     );

     return redirect()->route('profile.show', [$user->username]);
}

UpdateProfileCharacteristicsRequest.php

public function rules()
{
    return [
        'date_of_birth' => ['date'],
    ];
}
3 Answers

Since you are sending the date in a custom format in the request, you will need to parse it to a format that matches the one in the database column before inserting it:

 $user->update(
 [
    'date_of_birth' => Carbon::createFromFormat("d/m/Y", $request->date_of_birth)->format('Y-m-d'), // parse the right format here
    'age' => Carbon::now()->diffInYears(Carbon::createFromFormat("d/m/Y", $request->date_of_birth)),
    'updated_at' =>  Carbon::now()
 ]
 );

And for that date format to pass validation you can use the date_format:format rule instead of date:

public function rules()
{
    return [
        'date_of_birth' => ['date_format:"d/m/Y"'],
    ];
}

What is the column type in you database migration? If it is check if it DATE or DATETIME or TIMESTAMP, It is supposed to be DATE hence you can format your date to be Y-m-d.

If you are to save a DATE to DB it should be in the format of Y-m-d.

so try this:

public function updateProfileCharacteristics(Request $request)
{

   $user = Auth::user();

   $user->update([
        'date_of_birth' => Date('Y-m-d',strtotime($request->date_of_birth)),
        'age' => Carbon::now()->diffInYears($request->date_of_birth),
        'updated_at' =>  Carbon::now()
     ]);

     return redirect()->route('profile.show', [$user->username]);
}
Related