I have Foo
Attribute that use getFooAttribute
method to format it before display but in some places, I need original attribute for it. So how can I do it?
从 v4.2 开始获取特定属性的原始值:
$originalFoo = $model->getOriginal('foo');
如果您想在大部分代码中使用mutator但有时想要访问原始值,您可以通过使用模型的getAttributes()方法获取所有属性然后从那里获取值来实现,例如:
$originalFoo = $model->getAttributes()['foo'];
If you want the raw field straight out of database skipping the mutator then
$mode->getRawOriginal('attribute')
is the way to go. $model->getOriginal()
will give you the mutator value not the raw data you want.
我正在使用 5.3,为此我使用$model->getOriginal()['foo']
for laravel 5 we can also use:
$model->getOriginal('foo')
credits to @bower
$model->getRawOriginal()
The getOriginal Method
Likelihood Of Impact: Low
The
$model->getOriginal()
method will now respect any casts and mutators defined on the model. Previously, this method returned the uncast, raw attributes. If you would like to continue retrieving the raw, uncast values, you may use thegetRawOriginal
method instead.
为我工作
$newProduct = $product[0]->getRawOriginal();
Actually looks all above are correct, just see if this is in array key [0] for example:
$originalFoo = $model[0]->getRawOriginal('foo');
Something that might be worth mentioning as well is that the Laravel model class overwrites the magic methods for __set
and __get
, so you can also retrieve the original
attribute dynamically ie $model->original
.
See https://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Eloquent/Model.php
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.