2016-10-06 180 views
2

我在數據庫中有3個不同的字段:city,state,country。如何在Eloquent中定義另一個屬性以從這3個字段返回一個字符串?在Eloquent中定義自定義屬性

第一種方法,但它不工作:

protected $address = ""; 

public function getAddress() : string { 
    return $this->city . $this->state . " - " . $this->country; 
} 

回答

9

如果你想有一個新的屬性這在模型中沒有定義,您需要將該屬性追加到模型中。

/** 
* The accessors to append to the model's array form. 
* 
* @var array 
*/ 
protected $appends = ['address']; 

,並定義屬性的方法:

/** 
* Get the address. 
* 
* @return string 
*/ 
public function getAddressAttribute() 
{ 
    return $this->city . $this->state . " - " . $this->country; 
} 
+0

它可以工作!!!!!!! – ln9187