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.
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'];
}
thanks a lot lizeshakya for your help. ` protected $dates` in the model works. The other solution works well too. Carbon is a really powerful class. Thank you again for your help