我需要在不使用 get Attribute 的情况下为我的 Laravel 模型添加一个额外的属性。我想以默认和自定义格式获取 created_at 属性。
default : created_at : 2018-07-25 15:38:56
second: 10 Days Ago
Run Code Online (Sandbox Code Playgroud)
如果我使用 getCreatedAtAttribute() 它会更改默认属性。
在您的模型中,添加以下内容:
protected $appends = ['readable_created_at'];
public function getReadableCreatedAtAttribute()
{
return $this->created_at; //or however you want to manipulate it
}
Run Code Online (Sandbox Code Playgroud)
之后,您可以像往常一样访问它,例如$user->readable_created_at.
在此处的Laravel 文档中阅读更多内容。