laravel - 如何在通知集合中获取日期格式
问题描述
我需要为集合定义日期格式。我试过这样,但它不起作用:
return response()->json($request->user()->notifications()->format('d/m/Y')->limit(7)->get());
如何为整个集合设置日期格式?
解决方案
我认为您正在使用数据库通知并且您想要格式化该created_at
字段。
要快速返回结果,您可以执行以下操作:
$notifications = $user->notifications()
->limit(7)
->get()
->each(function ($notification) {
$notification->formatted_created_at = $notification->created_at->format('d/m/Y');
});
我建议您正确执行并创建一个新的API 资源。
use Illuminate\Http\Resources\Json\JsonResource;
class NotificationResource extends JsonResource
{
/**
* Transform the notification into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
// ...
'formatted_created_at' => $this->created_at->format('d/m/Y'),
];
}
}
// In the controller action
$notifications = $user->notifications()
->limit(7)
->get();
return NotificationResource::collection($notifications);
推荐阅读
- angular - Angular9 debugElement.classes['my-class'] 现在返回 undefined
- ios - sceneView.delegate 和 sceneView.session.delegate 有什么区别?
- reactjs - 如何测试使用 React Hooks useHistory hook 和 Enzyme 的 React 组件?
- javascript - AddEventListener 到 svg 文件,而不是使其可点击的按钮
- multithreading - Allure 支持运行线程测试
- php - 无法在存档页面上显示侧边栏(Wordpress、Elementor Pro+GeneratePress)
- android - 重新启用定位服务
- youtube-api - 使用“mine”参数向 /youtube/v3/channels 请求返回一个空列表
- python - 将 Python 字典中的 JSON 值累积为数组
- javascript - Javascript - 无法访问 HTMLCollection 的项目?