Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporary property for Laravel Eloquent model

Tags:

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?

like image 304
Nick Avatar asked Mar 10 '14 10:03

Nick


People also ask

What is accessors and mutators in Laravel?

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.

What does get () do in Laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.

What is $cast in Laravel?

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.

What is $fillable in Laravel?

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.


2 Answers

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.

like image 145
Thomas Ruiz Avatar answered Sep 29 '22 10:09

Thomas Ruiz


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

like image 20
mopo922 Avatar answered Sep 29 '22 12:09

mopo922