laravel 视图中缺少时间数据的意外数据
Unexpected data missing on laravel view with time data
在我的 Horario 模型中,我有以下内容:
protected $fillable = [ "inicio", "fin", "tipo" ];
protected $dates = [
'created_at',
'updated_at',
'inicio',
'fin'
];
在控制器中我保存的时间如下:
$horario = new Horario;
$horario->inicio = Carbon::createFromFormat('H:i', $request->inicio);
$horario->fin = Carbon::createFromFormat('H:i', $request->fin);
$horario->tipo = $request->tipo;
$horario->save();
其中inicio和fin是时间类型的列,我可以这样保存到数据库中(格式H:i):
horario record on mysql
当我尝试在我的视图中显示它时 laravel 抛出错误:
ErrorException
Unexpected data found.
Unexpected data found.
Data missing (View: C:\wamp64\www\plataforma-
foodsys\resources\views\opciones_de_aplicacion.blade.php)
在我看来我有:
<td>{{$horario->inicio->format("H:i")}}</td>
<td>{{$horario->fin->format("H:i")}}</td>
我不明白为什么会抛出异常,记录在 table 上保存得很好,我正在尝试以正确的时间格式对其进行格式化。知道为什么会这样吗?
这是因为 Laravel 无法将 'H:i' 格式识别为 date
(因为它不是日期)。
它将尝试将其转换为具有 asDateTime($val)
(source) 函数的 Carbon
实例,该实例不接受 H:i
格式。
我建议将它们实现为 accessors。
从 protected $dates
数组中删除 inicio
和 fin
并将其放入您的模型中:
use Carbon\Carbon;
...
public function getInicioAttribute($val)
{
return Carbon::parse($val);
}
public function getFinAttribute($val)
{
return Carbon::parse($val);
}
你的代码应该可以工作。
在我的 Horario 模型中,我有以下内容:
protected $fillable = [ "inicio", "fin", "tipo" ];
protected $dates = [
'created_at',
'updated_at',
'inicio',
'fin'
];
在控制器中我保存的时间如下:
$horario = new Horario;
$horario->inicio = Carbon::createFromFormat('H:i', $request->inicio);
$horario->fin = Carbon::createFromFormat('H:i', $request->fin);
$horario->tipo = $request->tipo;
$horario->save();
其中inicio和fin是时间类型的列,我可以这样保存到数据库中(格式H:i):
horario record on mysql
当我尝试在我的视图中显示它时 laravel 抛出错误:
ErrorException
Unexpected data found.
Unexpected data found.
Data missing (View: C:\wamp64\www\plataforma-
foodsys\resources\views\opciones_de_aplicacion.blade.php)
在我看来我有:
<td>{{$horario->inicio->format("H:i")}}</td>
<td>{{$horario->fin->format("H:i")}}</td>
我不明白为什么会抛出异常,记录在 table 上保存得很好,我正在尝试以正确的时间格式对其进行格式化。知道为什么会这样吗?
这是因为 Laravel 无法将 'H:i' 格式识别为 date
(因为它不是日期)。
它将尝试将其转换为具有 asDateTime($val)
(source) 函数的 Carbon
实例,该实例不接受 H:i
格式。
我建议将它们实现为 accessors。
从 protected $dates
数组中删除 inicio
和 fin
并将其放入您的模型中:
use Carbon\Carbon;
...
public function getInicioAttribute($val)
{
return Carbon::parse($val);
}
public function getFinAttribute($val)
{
return Carbon::parse($val);
}
你的代码应该可以工作。