php - 使用 Carbon 将日期保存到数据库中
问题描述
我还是 Laravel 的新手。目前,我正在学习和研究 Carbon。我已经查看了所有文档和其他解决方案,但我仍然不明白。我希望有人可以逐步教我如何纠正或改进我的代码。
投诉控制器.php
public function store(Request $request)
{
if (count($request->defect_id) > 0) {
foreach($request->defect_id as $item=>$v) {
$data = array(
'defect_id' => $request->defect_id[$item],
'image' => $filename,
'description' => $request->description[$item],
'report_by' => Auth::user()->id,
'created_at' => Carbon::today()->toDateString(),
'updated_at' => Carbon::now()->toDateTimeString()
);
Complaint::insert($data);
我created_at
仅将字段保存为日期,没有时间,格式为(yy-mm-dd)
.
index.blade.php
<div class="panel-body">
<table class="table table-hover">
<thead>
<tr>
<th>Defect Name</th>
<th>Description</th>
<th>Image</th>
<th>Report Date</th>
<th>Due Date</th>
</tr>
</thead>
@foreach($complaint as $c)
<tr>
<td>{{$c->defect->name}}</td>
<td>{{$c->description}}</td>
<td><img src="{{ Storage::url('complaint/' . $c->image)}}" class="" alt="{{$c->image}}"></td>
<td>{{$c->created_at->toDateString()}}</td>
<td></td>
</tr>
@endforeach
</table>
</div>
我的日期仍然在表格中很好地显示,(yy-mm-dd)
但我希望日期的格式为 ,(dd/mm/yy)
所以我尝试使用这种代码{{$c->created_at->toDateString()->format("dd/mm/yy")}}
并出现错误,即Call to a member function format() on string
. 稍后,我需要为到期日期添加另一个字段并使用此功能addDays(30)
。那么,我需要做什么?我猜我需要在我的模型中添加另一个函数,但我不知道该怎么做。
解决方案
正如@Tim Lewis 所提到的,替换
{{ $c->created_at->toDateString()->format("dd/mm/yy") }}
至
{{ $c->created_at->format("dd/mm/yy") }}
AstoDateString()
在更改格式之前将其转换为字符串。
您也可以尝试使用标准 php 格式的日期时间,而不是Carbon类,
{{ date("d/m/Y", strtotime($c->created_at)) }}
至于您要添加新表数据列的第二个问题,
<tr>
<td>{{ $c->defect->name }}</td>
<td>{{ $c->description }}</td>
<td><img src="{{ Storage::url('complaint/' . $c->image)}}" class="" alt="{{$c->image}}"></td>
<td>{{ $c->created_at->format("dd/mm/yy") }}</td>
<td>{{ $c->created_at->addDays(30) }}</td>
</tr>
推荐阅读
- javascript - 回调函数的作用域/this
- c# - 以时间间隔轮询时检测变量的特定值
- batch-file - for循环内的字符串替换
- java - 轮询客户端连接的正确方法是什么——Apache Thrift Server
- .net - 使用 DbContext 是否安全,而后者又在 Blazor Server 应用程序中使用 HttpContext?
- storybook - 故事书类型的 REACT vs REACT_PROJECT vs WEBPACK?
- php - Laravel 6.2:如何更改 Laravel 邮件中的 [from address] 字段
- python - tkinter.tclError 未知选项“-bd”
- python - 如何计算python数据框中整个字符串(不是子字符串)的出现次数?
- c - Scanf 在 VS Code 中无法按预期工作