Reputation: 79
<?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');
}
}
Error :
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '26/10/1988' for column 'born' at row 1 (SQL: update
user_information
How to update :
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);
}
I send the born date d/m/Y format from user interface. When i store this data in mysql, i ve to reformat to Y-m-d..
I googled and found the mutators : https://laravel.com/docs/5.3/eloquent-mutators
I added setNameAttribute function to UserInformation model. And i refreshed the page then tried again. But nothing changed. I got the same error.
How can i fix this problem ?
p.s. : I am using Laravel 5.3
Upvotes: 0
Views: 469
Reputation: 40653
Laravel has native support for date fields. Try this instead:
class UserInformation extends Model {
protected $dates = [
'created_at',
'updated_at',
'born'
];
//Rest of model without mutator
}
Upvotes: 0
Reputation: 79
Here is the answer :
Laravel 5 mutators only work when I create a record and not when I update a record
I changed the $user->userInformation()->update(
to $user->userInformation->update(
and it works.
Upvotes: 0
Reputation: 11906
Use carbon parse
.
public function setBornAttribute($value)
{
$this->attributes['born'] = Carbon::parse($value);
}
Upvotes: 1
Reputation: 716
Change the set function to:
public function setBornAttribute($date) {
$this->attributes['born'] = Carbon::createFromFormat('d/m/Y', $date)->format('Y-m-d');
}
Upvotes: 0
Reputation: 81
You must set the property $dateFormat on your model as follow:
protected $dateFormat = 'Y-m-d';
Check the documentation about date mutators
Upvotes: 0