Php 将日期从表单更新到数据库时出现问题
我正试图更新数据库中的“出生日期”列,当我提交表格时,我收到了这个错误Php 将日期从表单更新到数据库时出现问题,php,laravel,validation,Php,Laravel,Validation,我正试图更新数据库中的“出生日期”列,当我提交表格时,我收到了这个错误 DateTime::__construct(): Failed to parse time string (25/03/1995) at position 0 (2): Unexpected character 现在在我的刀片中,我将出生日期格式化为显示d/m/Y,更新时我认为它会更新Y/m/d,因为当我从刀片中删除格式功能时,它工作正常。因此,我需要有关如何在数据库中使用格式('d/m/Y')进行更新以及如何在表单请求验
DateTime::__construct(): Failed to parse time string (25/03/1995) at position 0 (2): Unexpected character
现在在我的刀片中,我将出生日期格式化为显示d/m/Y,更新时我认为它会更新Y/m/d,因为当我从刀片中删除格式功能时,它工作正常。因此,我需要有关如何在数据库中使用格式('d/m/Y')进行更新以及如何在表单请求验证中正确验证它的帮助。感谢您的帮助。这是我的密码
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') : "" }}">
UpdateProfileCharacteristicsRequest.php
public function rules()
{
return [
'date_of_birth' => ['date'],
];
}
数据库迁移中的列类型是什么?如果是检查日期、日期时间或时间戳,则应为日期,因此您可以将日期设置为Y-m-d。由于您在请求中以自定义格式发送日期,因此在插入之前,您需要将其解析为与数据库列中的格式相匹配的格式:
$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()
]
);
要使该日期格式通过验证,您可以使用date\u格式:format
规则,而不是date
:
public function rules()
{
return [
'date_of_birth' => ['date_format:"d/m/Y"'],
];
}
如果要将日期保存到DB,则应采用Y-m-d格式 所以试试这个:
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]);
}
澄清:
format()
函数只适用于Carbon对象,它是$userForShowProfile->date\u of_birth
一个Carbon对象吗?Illumb\Support\Carbon@638323200这是我转储它时得到的。的确如此。它在blade中很好地格式化了它,但当我尝试更新它时,我得到了错误。你的确切意思是什么?好的,尝试在你的用户模型中转换。受保护的$casts=['出生日期=>'日期',];并在此处查看更多信息DateTime::uu构造():未能分析位置0(2)处的时间字符串(1988年3月25日):意外字符供应商\nesbot\carbon\src\carbon\Traits\Creator.php:81,第81行为父::u构造($time?:'now',static::safeCreateDateTimeZone($tz)?:null);如果要将日期保存到DB,则应采用Y-m-d格式。所以试试这个公共函数updateProfileCharacteristics(Request$Request){$user=Auth::user();$user->update(['date\u of_birth'=>date('Y-m-d',strotime('Request->date\u of_birth)),'age'=>Carbon::now()->diffInYears('Request->date\u of_of_of_birth'),'updated\u at'=>Carbon::now());return redirect()->route('profile.show',[$user->username]);}
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]);
}