Home > Mobile >  Laravel 9 Mutating Attribute not returning mutated attribute
Laravel 9 Mutating Attribute not returning mutated attribute

Time:09-11

Environment

  • Laravel 9
  • php 8.0

I have this mutator function to transform a value from 4 decimal places to 2 decimal places. I want to test out but the Attribute::make function not returning value, below is code for the model

class SubjectWithFee extends Model
{
    protected $table = 'sjfee';
    protected $primaryKey = 'IndexID';

    protected $fillable  = [
        'Amount',
        'CurrencyID',
        'ProgramID',
        ];

    public $timestamps = false;

    protected function Amount(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => sprintf('%0.2f', $value),
        );
    }

Although when I did the test it access the attribute correctly when putting dd('test') before the return but on the get function cannot be access

Anyone knows the problem?

Update

The column "Amount" starts with capital letter

Initially the source code was from laravel version 5 and someone upgraded to 9.

Update 2

All my setters are working, but only getters are not.

CodePudding user response:

Try this different approach, instead of the current function you have:

public function getAmountAttribute($value)
    {
        return sprintf('%0.2f', $value);

    }

CodePudding user response:

Add the attribute name to the appends property of your model.


Appending Values To JSON

Occasionally, when converting models to arrays or JSON, you may wish to add attributes that do not have a corresponding column in your database. To do so, first define an accessor for the value:

After creating the accessor, add the attribute name to the appends property of your model. Note that attribute names are typically referenced using their "snake case" serialized representation, even though the accessor's PHP method is defined using "camel case":

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['amount'];
}
  • Related