Yohan Hirimuthugoda
Yohan Hirimuthugoda

Reputation: 1051

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

Upvotes: 2

Views: 3297

Answers (2)

Yohan Hirimuthugoda
Yohan Hirimuthugoda

Reputation: 1051

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.

Upvotes: 5

Travis Britz
Travis Britz

Reputation: 5552

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

Upvotes: 1

Related Questions