zoransa's avatar

Get raw attribute from database in form input

How to use in forms database values from models not modified trough mutators

Here is the problem.

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

Let's say in database nothing is 'capitalized' and that form should be in value={{ $model->first_name }} BUT it goes trough the function where 'raw' value is modified

0 likes
4 replies
zoransa's avatar

since attributes are not visible I tried $model->attributes['first_name'] I get null of course it is only possible to do it within the class as $this->attributes['first_name']

Snapey's avatar

You could create another Accessor?

public function getRawFirstNameAttribute()
    {
        return $this->attributes['first_name'];
    }

Personally, I would not do this, I would rename the other accessor so that the UC version has a different name.

2 likes
zoransa's avatar
zoransa
OP
Best Answer
Level 23
>>> $a = Fragrantica\Models\Accord::first();
=> Fragrantica\Models\Accord {#757
     id: 1,
     name: "alcohol",
     slug: "alcohol",
     description: null,
     color: null,
     created_at: "2016-02-29 10:50:21",
     updated_at: "2016-02-29 10:50:21",
   }
>>> app()->setLocale('pl');
=> null
>>> $a->name
=> "alkoholowy"
>>> $a->getAttribute('name')
=> "alkoholowy"
>>> $a->getAttributeValue('name')
=> "alcohol"

I found it $model->getAttributeValue($key) is the way to access 'raw' value and in forms instead of attributes actually it is much better to use getAttributeValue if you use any kind of mutators.

I have mutator on name and description in the case that locale is not 'en' translations are stored in separate table and morphed to get and set attribute update relationship instead of main model but this way we made website codebase absolutely the same for any language.

jester66's avatar

I think what you should be using is getRawOriginal('attribute_name') - at least in my laravel 10.38 install the other methods go through the mutator

1 like

Please or to participate in this conversation.