2017-05-25 45 views
0
<?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'); 
    } 
} 

错误:Laravel限定的Mutator

SQLSTATE [22007]:无效日期时间格式:1292不正确的日期值: '26 /一千九百八十八分之一十' 列 '在行1出生'(SQL :更新 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 ..

我一派,发现存取器: https://laravel.com/docs/5.3/eloquent-mutators

我加入setNameAttribute功能UserInformation模型。我刷新了页面,然后再次尝试。但没有任何改变。我得到了同样的错误。

我该如何解决这个问题?

p.s. :我使用Laravel 5.3

+0

你应该存储到数据库 –

回答

0

改变设定功能:

public function setBornAttribute($date) { 
    $this->attributes['born'] = Carbon::createFromFormat('d/m/Y', $date)->format('Y-m-d'); 
} 
+0

我调试的代码... getBornAttribute调用之前将其转换为Y-M-d但setBornAttribute不打电话时更新。 – Ozgun

+0

你如何设定出生的价值?如果你使用'fill'函数它不会执行,你应该使用'$ model-> born = $ value;' – Aboudeh87

1

使用碳parse

public function setBornAttribute($value) 
{ 
    $this->attributes['born'] = Carbon::parse($value); 
} 
0

Laravel对日期字段具有本机支持。试试这个:

class UserInformation extends Model { 

    protected $dates = [ 
    'created_at', 
    'updated_at', 
    'born' 
]; 

//Rest of model without mutator 

}