Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mvnobrega's avatar

Date format in notifications table

I need to define the date format for a collection. I tried it that way, but it doesn't work:

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

How could I set the date format for an entire collection?

0 likes
1 reply
mvnobrega's avatar
mvnobrega
OP
Best Answer
Level 3

A member of another forum gave the solution. Follow for those who need it:

To return the results fast, you might do something like this:

$notifications = $user->notifications()
    ->limit(7)
    ->get()
    ->each(function ($notification) {
        $notification->formatted_created_at = $notification->created_at->format('d/m/Y');
    });

I suggest that you do it properly and create a new API resource.

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);

Please or to participate in this conversation.