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?
Accessors and mutators allow you to format Eloquent attributes when retrieving them from a model or setting their value. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model.
This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.
From Laravel Documentation: Attribute Casting The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to.
The fillable property is used inside the model. It takes care of defining which fields are to be considered when the user will insert or update data. Only the fields marked as fillable are used in the mass assignment. This is done to avoid mass assignment data attacks when the user sends data from the HTTP request.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With