Temporary property for Laravel Eloquent model

2019-04-04 00:14发布

I have a Laravel Eloquent model User, which has a table with username and email columns. I need to add a property for the model on runtime, something like $user->secure. This property doesn't need to go to database.

When i add this property and hit $user->save() i get an error saying i don't have database column 'secure'. I can unset 'secure' before save but somehow it feels there should be a better way to do so. Any suggestions?

3条回答
淡お忘
2楼-- · 2019-04-04 00:40

For those who still find this post (like I did), you may need to explicitly declare the property as null to prevent it from being automatically added to the attributes array, and thus being added to INSERT/UPDATE queries:

class User extends Eloquent {
    public $secure = null;

    // ...
}

Source: http://laravel.io/forum/02-10-2014-setting-transient-properties-on-eloquent-models-without-saving-to-database

查看更多
相关推荐>>
3楼-- · 2019-04-04 00:49

Just add an attribute to your class.

class User extends Eloquent {
  public $secure;

  // ...
}

Note that it is better to declare it protected and add corresponding accessors and mutators (getSecure and setSecure methods) to your model.

查看更多
再贱就再见
4楼-- · 2019-04-04 00:50

If you intend to make use of that add-on property, then $append will blow your mind.

http://laraveldaily.com/why-use-appends-with-accessors-in-eloquent/

查看更多
登录 后发表回答