2017-05-25 43 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 

}