laravelmutators

Laravel mutators on specific situations


As I understand, mutators change your attribute on save function (create or update). Can I make mutator just for atrribute display to users, but leave default values on save function ?


Solution

  • In Eloquent Model when you do this:

    public function getSomeNameAttribute($value)
    {
        return ucfirst($value);
    }
    

    That ^ will mutate the value for showing it later in views and it won't affect what is stored in DB table.

    And also if you use a setter setSomeNameAttribute($value) you can pull the actual value from db table with:

    $model->getOriginal('attribute_name'); // Laravel V. ^5.*
    

    or

    $model->getRawOriginal('attribute_name'); // Laravel V. ^8.*