phplaraveleloquentaccessormutators

Laravel Accessors and Mutators not working for Camel Case table fields names


My table looks like below:

CREATE TABLE IF NOT EXISTS `ProductCategoryImage` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,  
  `productCategoryId` INT(11) NOT NULL,
  `imageName` VARCHAR(255) NOT NULL,  
  `thumbnailName` VARCHAR(255) NULL DEFAULT NULL,
  `location` TINYINT(2) NOT NULL DEFAULT 1,
  `status` TINYINT(2) NOT NULL DEFAULT 1,
  `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updatedAt` TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `deletedAt` DATETIME NULL DEFAULT NULL,
  `createdById` INT(11) NOT NULL DEFAULT -1,
  `updatedById` INT(11) NULL DEFAULT NULL,
  `deletedById` INT(11) NULL DEFAULT NULL
);

Inside the ProductCategoryImage model I have written down below two methods:

public function getThumbnailNameAttribute($value)
{
    return self::getThumbnailUrl($value);    
}
public function setThumbnailNameAttribute($value)
{
    $this->attributes['thumbnailName'] = $value;
}

Laravel won't execute above two methods to customize my table field value.

ProductCategoryImage model extends from custom BaseModel and BaseModel extends from Eloquent.

Doesn't Laravel has event handler methods like beforeFind(), afterFind(), beforeSave(), afterSave()?


Solution

  • One of my team member achieved it using the toArray() method:

    public function toArray()
    {
        $toArray = parent::toArray();
        $toArray['thumbnailName'] = $this->thumbnailName;
        return $toArray;
    }
    
    public function getThumbnailNameAttribute($value)
    {
        return self::getThumbnailUrl($value);
    }
    

    Worked like charm.