Skip to content

Custom datetime casting works, but not if you define custom format #2655

Closed
@apeisa

Description

Thanks to #2653 casting works now, but not in all cases. When using date casts, you can also define the format in the string format, like this (docs):

   protected $casts = [
        'mydate' => 'datetime:j.n.Y H:i',
    ];

When using cast like that, it doesn't work. Without formatting set, it does work as expected:

   protected $casts = [
        'mydate' => 'datetime',
    ];

Here is simple class that can be used for testing:

<?php

namespace App\Models;

use Carbon\Carbon;
use MongoDB\Laravel\Eloquent\Model;

class Car extends Model
{
    protected $guarded = [];

    protected $casts = [
        'sold_at' => 'datetime:j.n.Y H:i',
    ];

    public function sell()
    {
        $this->sold_at = Carbon::now();
        $this->save();
        return $this;
    }
}

And to test this run these commands on Tinker:

> $car = App\Models\Car::create();
= App\Models\Car {#8065
    updated_at: MongoDB\BSON\UTCDateTime {#8071
      +"milliseconds": "1698741994126",
    },
    created_at: MongoDB\BSON\UTCDateTime {#8071},
    _id: MongoDB\BSON\ObjectId {#8075
      +"oid": "6540beea13e41d27cd036b52",
    },
  }

> $car->sell();
= App\Models\Car {#8065
    updated_at: MongoDB\BSON\UTCDateTime {#8063
      +"milliseconds": "1698742000466",
    },
    created_at: MongoDB\BSON\UTCDateTime {#8071
      +"milliseconds": "1698741994126",
    },
    _id: MongoDB\BSON\ObjectId {#8075
      +"oid": "6540beea13e41d27cd036b52",
    },
    sold_at: Illuminate\Support\Carbon @1698742000 {#8066
      date: 2023-10-31 08:46:40.461974 UTC (+00:00),
    },
  }

As you can see the sold_at has Carbon object in database, it should be MongoDB\BSON\UTCDateTime. If you remove the :j.n.Y H:i part from $casts then it works as expected. Here is tinker output without the date formatting:

App\Models\Car {#8065
    updated_at: MongoDB\BSON\UTCDateTime {#8063
      +"milliseconds": "1698742105625",
    },
    created_at: MongoDB\BSON\UTCDateTime {#8071
      +"milliseconds": "1698742103464",
    },
    _id: MongoDB\BSON\ObjectId {#8075
      +"oid": "6540bf576b0d0e380a0cd942",
    },
    sold_at: MongoDB\BSON\UTCDateTime {#8078
      +"milliseconds": "1698742105624",
    },
  }

Originally posted by @apeisa in #2653 (comment)

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions