首页 > 解决方案 > 如何在通知集合中获取日期格式

问题描述

我需要为集合定义日期格式。我试过这样,但它不起作用:

return response()->json($request->user()->notifications()->format('d/m/Y')->limit(7)->get());

如何为整个集合设置日期格式?

标签: laravel

解决方案


我认为您正在使用数据库通知并且您想要格式化该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);


推荐阅读