Martin AJ
Martin AJ

Reputation: 6697

Why doesn't Carbon work in the loop?

Here is my code:

foreach($tasks as &$task){
    dd(Carbon::parse($task->created_at)->diffForHumans());
}

It prints "2 hours ago". All fine.

Now when I remove dd(), it throws error:

foreach($tasks as &$task){
    $task->created_at = Carbon::parse($task->created_at)->diffForHumans();
}

/*It throws:
    (1/1) InvalidArgumentException
     A two digit month could not be found
     Data missing

Does anybody how can I fix it?

Upvotes: 0

Views: 93

Answers (1)

Maraboc
Maraboc

Reputation: 11083

To know created_at is an instance of Carbon so no need for the parse, also you can do this directly from the view if you want

{{$task->created_at->diffForHumans()}}

It fails because Laravel want to parse 2 hours ago when you did $task->created_at = Carbon::parse($task->created_at)->diffForHumans(); to put an instance of Carbon in the created_at field.

Upvotes: 1

Related Questions