I am using Laravel 5.7 and Postgresql for the database. Got the problem with eloquent error: carbon trailing data, caused by row data which has created_at/updated_at with millisecond on it.
I have tried this solution from another thread: Laravel model Trailing Data when save the model But got error, "Data missing".
Here is one sample of model which has created_at/updated_at field:
class Department extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'hr_department';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'message_main_attachment_id',
'name',
'complete_name',
'active',
'company_id',
'parent_id',
'manager_id',
'note',
'color',
'create_uid',
'create_date',
'write_uid',
'write_date',
];
const CREATED_AT = 'create_date';
const UPDATED_AT = 'write_date';
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'create_date' => 'datetime',
'write_date' => 'datetime',
];
public function DepartmentParent() {
return $this->belongsTo('App\Department', 'parent_id');
}
public function getDepartmentParentNameAttribute() {
if ($this->DepartmentParent) {
return $this->attributes['department_parent_name'] = $this->DepartmentParent->name;
}
return null;
}
}
The action in controller to show json result for api:
/**
* Display a listing of the resource.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function list(Request $request)
{
$httpCode = 200;
$message = "Here is the department list";
$modelData = null;
try {
$query = Department::whereRaw('0 = 0');
if ($request->active)
$query = $query->where('active', $request->active);
if ($request->name)
$query = $query->where('name', $request->name);
$query = $this->setRestFilter($query, $request);
$modelData = $query->get();
} catch (Exception $e) {
$httpCode = $e->getCode();
$message = $e->getMessage();
}
return response()->json([
'message' => $message,
'modelData' => $modelData
], $httpCode);
}
Is there any configuration so the carbon does not read the millisecond from database? Or need to prevent laravel from saving the millisecond at created_at/updated_at field? And how to do that globally?