简体   繁体   中英

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()?

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.

Accessors/mutators are only called when you access a property on a model. These attributes would be used like this:

$name = $image->thumbnail_name; // getThumbnailNameAttribute()

$image->thumbnail_name = 'foo'; // setThumbnailNameAttribute()

The magic property name will be the snake_case version of your StudlyCase attribute name.

Since your accessor's property name isn't thumbnail_name , Laravel won't find the original value automatically. You can get it from the model's attributes array directly:

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

Note that you still need to call save() for changes made by a mutator to appear in your database.

If you want certain things to happen automatically whenever a model is saving , creating , restored , etc. then you can listen for the appropriate lifecycle event: https://laravel.com/docs/5.7/eloquent#events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM