<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class UserInformation extends Model {
/**
* The table associated with the model.
*
* @var string
*/
protected $table = "user_information";
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title',
'first_name',
'last_name',
'img_path',
'born',
'gender',
'address',
'country_id',
'about',
'institution',
'area_of_expertise',
'cv_path',
'facebook',
'twitter',
'instagram',
'linkedin',
'university',
'university_graduated_at',
'md',
'md_graduated_at',
'associate_professor',
'associate_professor_graduated_at'
];
public function setBornAttribute($date) {
$this->attributes['born'] = Carbon::createFromFormat('Y-m-d', $date);
}
public function users() {
return $this->belongsTo('App\User', 'user_id', 'id');
}
}
错误:
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '26/10/1988' for column 'born' at row 1 (SQL: update
user_information
如何更新:
public function updateUser($request, $id) {
$user = User::with('userInformation')->findOrFail($id);
$user->update(array_filter($request->all()));
$user->userInformation()->update(array_filter($request->only([
'title',
'first_name',
'last_name',
'img_path',
'born',
'gender',
'address',
'country_id',
'about',
'institution',
'area_of_expertise',
'cv_path',
'facebook',
'twitter',
'instagram',
'linkedin',
'university',
'university_graduated_at',
'md',
'md_graduated_at',
'associate_professor',
'associate_professor_graduated_at'
]), 'strlen'));
return User::with('userInformation')->findOrFail($id);
}
我从用户界面发送出生日期 d/m/Y 格式。当我将这些数据存储在 mysql 中时,我必须重新格式化为 Y-m-d..
我用谷歌搜索并找到了更改器(mutator): https://laravel.com/docs/5.3/eloquent-mutators
我将 setNameAttribute 函数添加到 UserInformation 模型中。我刷新了页面然后再次尝试。但一切都没有改变。我也遇到同样的错误。
如何解决这个问题?
附: :我使用的是 Laravel 5.3
最佳答案
使用碳解析
。
public function setBornAttribute($value)
{
$this->attributes['born'] = Carbon::parse($value);
}
关于php - Laravel 定义 Mutator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44178588/