Warm tip: This article is reproduced from stackoverflow.com, please click
datetime eloquent laravel-5.8 php-carbon timestamp

my query works with timestamp but gives an error with datetime

发布于 2020-03-27 10:24:44

I have a mysql table with the following columns

name | dateone | mail | created_at

the "dateone" field is date type

the "created_at" field is timestamp type

in my controller I have a method to group the result by date

$users = Post :: orderBy ('dateone') -> get () -> groupBy (function ($ item) {

 return $ item-> created_at-> format ('Y-m-d');

it works, but, when I replace

return $ item-> created_at-> format ('Y-m-d');

by

return $ item-> dateone-> format ('Y-m-d');

I have the following error:

Call to a member function format() on string

is there a solution through Carbon or other to solve my problem ?

thank for any help.

Questioner
Zembla
Viewed
54
lizeshakya 2019-07-03 22:43

Yes, by default created_at and updated_at are in the Carbon Instance. You can use dateone as created_at by parsing it to the carbon instance.

$convertedDateOne = null;
if(!empty($item->dateone)){
    $convertedDateOne = Carbon::parse($item)->format('Y-m-d');
}

If you want the dateone to be the instance of Carbon every time, you can cast in the datetime format in the model.

Supposing the model name is Item.php

class Item extends Model{
   protected $dates = ['dateone'];
}