2015-11-28 121 views
2

訪問者將完美地完成他們對單個屬性的工作,但我需要一種方法來對所有屬性和自動執行Accessor/Getter作業。修改Laravel模型的所有屬性

其目的是我想替換一些字符/數字獲取屬性,然後打印出來。我可以從控制器內部手動完成,但是我認爲從模型側面和自動完成它會很棒。

像覆蓋getAttributes()方法:

public function getAttributes() 
{ 
    foreach ($this->attributes as $key => $value) { 
     $this->attributes[$key] = str_replace([...], [...], $value); 
    } 
    return $this->attributes; 
} 

但我每次都叫它型號$model->getAttributes();

任何方式自動幹辦呢?

+0

如何重寫構造和使用父:: __結構()?或者添加新的類擴展模型使用結構,並讓模型擴展該新類以適用於所有類。 –

+0

@TimvanUum其實我是這麼做的,但我認爲應該有錯誤,因爲它根本不會影響結果! – revo

+0

奇怪只是自己試了一下,確實不行。即使再次調用填充方法。 –

回答

5

嘗試類似:

public function getAttribute($key) 
{ 
    if (array_key_exists($key, $this->attributes) || $this->hasGetMutator($key)) { 
     if($key === 'name') return 'modify this value'; 
     return $this->getAttributeValue($key); 
    } 

    return $this->getRelationValue($key); 
} 

它完全覆蓋默認的方法,所以要小心一點。

編輯

還檢查了:http://laravel.com/docs/5.1/eloquent-mutators

+0

優秀的解決方案來覆蓋'getAttribute'。然而,在設置一個值時調用mutators,這在這裏不是目的。 – Bogdan

+0

你能否稍微解釋一下你的評論。或者,也許澄清爲什麼這個解決方案不起作用? –

+0

@shock_gone_wild您能否解釋爲什麼解決方案不起作用?你有錯誤嗎?你沒有得到你想要的結果嗎?該功能可以添加到特定的模型類(如用戶)或創建一個新的類(CustomBaseModel),擴展模型並將其添加到模型中,讓模型擴展該新類。將($ key ==='name')更改爲要更改或刪除以更改全部內容。使用:$ this-> getAttributeValue($ key);修改值 –

0

如何與每個創建運行它和更新事件。所以,你可以做這樣的事情:

public function boot() 
    { 
     Model::creating(function ($model) 
      return $model->getAttributes(); //or $this->getAttributes() 
     }); 
     Model::updating(function ($model) 
      return $model->getAttributes(); //or $this->getAttributes() 
     }); 
    } 
+0

'model :: creating()'在實例化模型時會觸發嗎? – revo

+0

在保存之前,您可以使用save()來替換更新和創建 –

+0

您錯了。我不會在儲蓄上做到這一點,但是要獲得。我談到訪問者而不是變種人。 – revo

1

我會去用以下辦法和重載__get方法的模型:

public function __get($key) 
{ 
    $excluded = [ 
     // here you should add primary or foreign keys and other values, 
     // that should not be touched. 
     // $alternatively define an $included array to whitelist values 
     'foreignkey', 
    ]; 

    // if mutator is defined for an attribute it has precedence. 
    if(array_key_exists($key, $this->attributes) 
     && ! $this->hasGetMutator($key) && ! in_array($key, $excluded)) { 
     return "modified string"; 
    } 

    // let everything else handle the Model class itself 
    return parent::__get($key); 
} 

}