Search code examples
laravel-8

I changed laravel collection to Array by toArray() function, My date format is changed


I created a collection then it changed it to Array by toArray() function. In the collection, my date is 2022-08-24 but after converting it into an array it returns 2022-08-23T00:00:00.000000Z value. Does anyone have any solution or reason behind this change?


Solution

  • Date Casting

    By default, Eloquent will cast the created_at and updated_at columns to instances of Carbon, which extends the PHP DateTime class and provides an assortment of helpful methods. You may cast additional date attributes by defining additional date casts within your model's $casts property array. Typically, dates should be cast using the datetime or immutable_datetime cast types.

    When defining a date or datetime cast, you may also specify the date's format. This format will be used when the model is serialized to an array or JSON:

    In your model:

        /**
         * The attributes that should be cast.
         *
         * @var array
         */
        protected $casts = [
            'created_at' => 'datetime:Y-m-d',
        ];