phplaraveldatetimephp-carbon

Cannot get correct date property from object on laravel using carbon


I'm working o a scheduelling app and I've run into a problem.

When I'm making an appointment I have to check for conflicting appointments, but for some reason, even though the date passed is correct, it's not passing through to the query.

I've managed to track to issue to this function

   public function getConflicting()
{
    //dd($this);

    return Requisition::where('date_start','<=', $this->date_end->toDateTimeString())
        ->where('date_end','>=', $this->date_start->toDateTimeString())
        ->get();
}

if I output the object I get this, and you can se the dates are correct

enter image description here

but if I try to acces the properties individually like i do in the query the time is not passed on

    dd($this->date_start);

enter image description here

I have defined theses date property in casts so they be casted correctly, I had initially casted as date, but later changed to datetime, but they still apear as date, is this a cache problem?

protected $casts  = [
    'date_start' => 'datetime:Y-m-d H:i:s',
    'date_end' => 'datetime:Y-m-d H:i:s',
];

enter image description here


Solution

  • Thanks for your comments, yes the database definition is in fact datetime, and it was getting a datetime from the database, as you can se in the fist picture, it was only setting the time to 0 when I accessed the properties individualy, that's why it was confusing to me.

    I need to cast as datetime, otherwise I get a string from the database, and I need to have a date to calculate the conflicting scheduling, but I will still have to convert it back to string again to display it. And your are right I shouldn't do that ToDatetimeString there it's was just one of my attemps of making it work.

    Sorry for the pictures, nothing about the problem there, just the content of the objects, but it was my ideia of showing and confirming the information i'm relaying so you could see that the contents the object were correct but when I accessed the porperties directly it was not.

    But I've actually figured it out, seemed like a complicated question but after all it was really simple, my casts definition was wrong.

    I had defined it as an array instead of a function. once done properly it works fine.

    protected function casts(): array
    {
        return [
            'date_start' => 'datetime:Y-m-d H:i:s',
            'date_end' => 'datetime:Y-m-d H:i:s',
        ];
    }