phplaravel-5.4eloquentmutators

Laravel 5.4 Mutator not working


I have a mutator which is not working, I've looked through here, tried some suggestions and yet nothing appears to get it working.

Here is my Model:

...

protected $fillable = [
    'energy_types'
];

...

public function getEnergyTypesAttribute($value)
{
    $types = explode(',', $value);
    $fuels = array();
    foreach($types as $type){
        switch ($type){
            case '2':
                $fuelType = 'Gas (Reticulated)';
                break;
            case '3':
                $fuelType = 'Gas (Bottled)';
                break;
            default:
                $fuelType = 'Electricity';
        }
        $fuels[] = array(   "id" => $type,
                            "name" => $fuelType);
    }

    return $fuels;
}

Stored in the database as so:

energy_types

1

1,2

1

Controller:

if($participant->isRetailer){
       $retail = Retailer::find($participant->id);
       $participant->energyTypes = $retail->energy_types;

If I do a dump here of $retail, energy_types is still just like so:

["energy_types"]=>
    string(3) "1,2"

I've tried changing how I get $retail, re-migrated, tried even setting an attribute (doesn't work also).

What am I doing wrong?


Solution

  • First, Mutator functions are like "setEnergyTypesAttribute".

    Your code snippets, however, is showing that you're trying to define an Accessor.

    Anyway, if you are trying to add a custom attribute to a Model when retrieving data from database, here is how you do it.

    ...
    protected $appends = ['foo'];
    ...
    public function getFooAttribute()
    {
        return $this->attributes['bar'] . ' foo'; 
    }
    

    where "bar" is an original attribute in the Model.

    Hope it helps.