Search code examples
laravel-5modelsextendphp-carbon

Extending Laravel's base model


In Laravel all models extend the base model.

The laravel eloquent models have a protected array attribute called $dates. Every date that is being added to this array is automatically converted to a Carbon instance.

I would like to extend the base model with similar functionality. For example with a protected $times attribute. All the time attributes would be converted to a Carbon instance

How would you do this?

Thanks in advance.


Solution

  • Thats easy whatever you want to do. Basic PHP knowledge.

    If you want to add some other fields to be converted to Carbon instances, simply add them to $dates array

    If you want to add some new parameters just extend laravel's Model as shown below

    <?php
    namespace App;
    
    class MyModel extends \Illuminate\Database\Eloquent\Model
    {
    
        protected $awesomness = [];
    
        /**
         *  override method
         *
         */
        public function getAttributeValue($key)
        {
            $value = $this->getAttributeFromArray($key);
    
            // If the attribute has a get mutator, we will call that then return what
            // it returns as the value, which is useful for transforming values on
            // retrieval from the model to a form that is more useful for usage.
            if ($this->hasGetMutator($key))
            {
                return $this->mutateAttribute($key, $value);
            }
    
            // If the attribute exists within the cast array, we will convert it to
            // an appropriate native PHP type dependant upon the associated value
            // given with the key in the pair. Dayle made this comment line up.
            if ($this->hasCast($key))
            {
                return $this->castAttribute($key, $value);
            }
    
            // If the attribute is listed as a date, we will convert it to a DateTime
            // instance on retrieval, which makes it quite convenient to work with
            // date fields without having to create a mutator for each property.
            if (in_array($key, $this->getDates()) && !is_null($value))
            {
                return $this->asDateTime($value);
            }
    
            //
            //
            // that's the important part of our modification
            //
            //
            if (in_array($key, $this->awesomness) && !is_null($value))
            {
                return $this->doAwesomness($value);
            }
    
            return $value;
        }
    
        public function doAwesomness($value)
        {
            //do whatever you want here
            return $value;
        }
    
    }
    

    Then all of your models just need to extend \App\MyModel class instead of \Illuminate\Database\Eloquent\Model