自定义模型属性Laravel 5.5

时间:2018-04-20 19:08:01

标签: php laravel

我正在检索用户信息:

 /**
 * User info
 * Retrieve the user info based on the Access Token
 *
 * @param Request $request
 */
public function user(Request $request)
{
    return $this->successResponse(request()->user(), 200);
}

我想在模型中添加一个不在db中的属性,并且属性只是一个常数值。我该怎么办?

我尝试将公共变量' gravatar'添加到用户模型中,但它们不会被检索到:

class User extends Authenticatable 
{
use Notifiable, HasApiTokens;

public $gravatar = "hi";

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token','id','created_at','updated_at',
];


public function ideas()
{
    return $this->hasMany(Idea::class);
}

}

1 个答案:

答案 0 :(得分:2)

您要做的是在Eloquent课程中设置访问者。如果您以后在获取模型数据时想要这样做,则可以在类中设置$appends属性。

通过将此添加到您的班级来设置访问者:

public function getFooAttribute() {
    return 'foobar';
}

然后使用$model->foo访问该属性。更改Foo中的getFooAttribute以更改属性的名称。

如果您以后想要在尝试获取所有属性时或在尝试对其进行jsonify时访问它,请将其添加到$appends属性:

protected $appends = ['foo'];

https://laravel.com/docs/5.6/eloquent-serialization#appending-values-to-json

的文档中对此进行了解释