Serialize computed property Carbon instance

Posted 1 month ago by smnwk

Hi,

my model offers a computed property called "departureTime"; if a departure time is available, it will be returned as a Carbon instance. By serializing I just want to get the date so I added a cast in my $date property (I also tried $casts) but nevertheless it does not work.

class Track extends Model
{
    protected $dates = ['time', 'arrivalTime', 'departureTime'];

    /** ... other stuff ... **/

    public function getDepartureTimeAttribute() {
        if(!$this->isDriving) {
            return null;
        }

        $lastNullPosition = Track::where([
            ['speed', 0], ['created_at', '<=', $this->created_at]
        ])->orderBy('id', 'desc')->first();

        return $lastNullPosition->time;
    }
}
"departureTime":{"date":"2018-12-15 16:33:51.000000","timezone_type":3,"timezone":"Europe\/Berlin"}

Maybe someone could help me.

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.