prgrm
prgrm

Reputation: 3835

Cannot set Carbon variable in Laravel

I want to set the value of an item to hours and minutes like this:

foreach ($items as $item){
    if($item->created_at->gte($begin_date) && $item->created_at->lte($end_date))
    {
        $item->created_at = $item->created_at->format('H:m');
        $sorted_items[] = $item;
    }
}

When I use dd($item->created_at->format('H:m')) it shows the hour and minute correctly, however when I try to set $item->created_at to the hour and minute it throws me this error:

InvalidArgumentException in Carbon.php line 582:
Unexpected data found.
Data missing

Upvotes: 1

Views: 918

Answers (1)

Robin Dirksen
Robin Dirksen

Reputation: 3422

I think it can't use created_at, this is defined in the model.php. If you use another attribute, something like created_at_formatted it should work.

$item->created_at_formatted = Carbon::createFromFormat('Y-m-d H:i:s', $item->created_at)->format('H:m');

Laravel uses the protected $dates; in your Model to assign a Carbon instance, so everytime you call $item->created_at it will return Carbon::parse($item->created_at). This can't be done cause you changed the data to incorrect values (H:m).

Hope this works!

Upvotes: 3

Related Questions