Search code examples
phplaraveleloquentaccessorlumen

Laravel attribute accessor capital letter is ignored


I am using Lumen framework. I have one problem, I need to set custom accessor for attribute, but the problem is that column in database starts with capital letter.
For example Logo.And in case of first capital letter, accessor is not called while retrieving object, I have tried with several columns, columns with name starts from small letter works perfectly.

 public function getLogoAttribute($value) 

This accessor doesn't work ,because name of column is Logo
I cannot change the name of columns in the database, but need to use accessors in my application.
I understand that I can change sources of Eloquent framework, but maybe there any other way to get it working.
Thanks.


Solution

  • I have spent several hours trying to find answer surfing the net, but than decided to find this part in code by myself.
    I have found it.

    It is located in vendor/illuminate/database/Eloquent/Model
    Method public function attributesToArray()

    Modify the part of this method like this

     $mutatedAttributes = $this->getMutatedAttributes();
    
            // We want to spin through all the mutated attributes for this model and call
            // the mutator for the attribute. We cache off every mutated attributes so
            // we don't have to constantly check on attributes that actually change.
            foreach ($mutatedAttributes as $key) {
                if (! array_key_exists($key, $attributes) ) {
                    if(array_key_exists(ucfirst($key), $attributes)) {
                        $key = ucfirst($key);
                    }
                    else {
                        continue;
                    }
                }
    

    If you have several capital letters in column name this will not work.

    This bad solution for this problem, just name you database columns according to convention and you won't have any problems ( I have ability to change column name in my case).

    UPDATE

    You can also modify class like this

        /**
         * Indicates if the model mutated attributes can have different case from ex. User_comments instead of user_comments.
         *
         * @var bool
         */
        public $upperCaseMutatedAttributes = false;
    
     if($this->upperCaseMutatedAttributes && array_key_exists(ucfirst($key), $attributes)) {
                        $key = ucfirst($key);
                    }
    

    You can override this variable in your class.