Search code examples
phplumenphp-carbon

Lumen disable carbon date


I need records date not to be carbon instance.

 $soldier = Soldier::find($id);

 dd($soldier->soldier_data->pluck('created_at'));

running this code will output :

object(Illuminate\Support\Collection)#71 (1) { ["items":protected]=> array(4) { [0]=> object(Carbon\Carbon)#66 (3) { ["date"]=> string(26) "2017-08-03 13:27:47.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } [1]=> object(Carbon\Carbon)#65 (3) { ["date"]=> string(26) "2017-08-03 13:28:13.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } [2]=> object(Carbon\Carbon)#77 (3) { ["date"]=> string(26) "2017-08-03 13:28:15.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } [3]=> object(Carbon\Carbon)#63 (3) { ["date"]=> string(26) "2017-08-03 13:28:15.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } } } 

this return created_at as carbon instance . i have also leaved dates array empty .but no chance.

class SoldierData extends Model {

    protected $fillable = [];

    protected $dates = [];

    protected $table = 'soldier_data';

Solution

  • Fix

    You can cast it directly in SoldierData class.

    protected $casts = [
        'created_at' => 'string',
    ];
    

    The reason

    The reason of not affecting casts by dates attribute is the following one. Eloquent class HasAttribute contains default dates: protected $dates = [];. And getDates method

    public function getDates()
    {
        $defaults = [static::CREATED_AT, static::UPDATED_AT];
    
        return $this->usesTimestamps() ? array_merge($this->dates, $defaults) : $this->dates;
    }
    

    So this two properties created_at and updated_at are by default casted as dates without any definitions. Then have a look at attributesToArray: first two dates are casted as dates, then it can be overwritten.

     public function attributesToArray()
     { 
        // If an attribute is a date, we will cast it to a string after convert$
        // to a DateTime / Carbon instance. This is so we will get some consist$
        // formatting while accessing attributes vs. arraying / JSONing a model.
        $attributes = $this->addDateAttributesToArray(
            $attributes = $this->getArrayableAttributes()
        );
    
        $attributes = $this->addMutatedAttributesToArray(
            $attributes, $mutatedAttributes = $this->getMutatedAttributes()
        );
    
        // Next we will handle any casts that have been setup for this model an$
        // the values to their appropriate type. If the attribute has a mutator$
        // will not perform the cast on those attributes to avoid any confusion.
        $attributes = $this->addCastAttributesToArray(
            $attributes, $mutatedAttributes
        );
    

    This method attributesToArray is called from Eloquent\Model::toArray method. That is the internal kitchen of typecasting.