zachleigh/laravel-property-bag

Have more control to choose when the properties should persist

Closed this issue · 1 comments

Is there a way to add property bags as a new model is created ?
Currently it looks like the model must be existing first

$user = new User($data);
$user->save();
//Then add settings
$user->settings(['valid_date_or_birth',false]);

There is no way to add those settings prior to saving ?

$user = new User();
$user->settings(['valid_date_or_birth',false]);  
//The problem is that this will trigger a SQL query
//I am sure a workaround could be to set the settings first before adding any other data
// $user->save(); here then filling the data later on
$user->fill($data); // include operations that will be affected by the settings
$user->save();

One of the issues I have been running into is that I have settings in my model that affect some attributes and mutators. For example. If this valid_date_or_birth setting affect how a date format should change in either an accessor or a mutator. Because the user would not have an ID at the time this setting is stored, It will fail.
The problem is that as soon as the settings is set, it triggers a SQL query. However I would like to set those settings so that I can do extra computations (especially for models not currently saved)
and save those settings when its time to do so

class User extends Model{
    public function getDateAttribute(){
        //Perform operation based on the user settings
    }
    public function setDateAttribute(){
        //Perform operation based on the user settings
    }
}

Sorry about the lateness of this reply. Life hasn't given me much time for open source lately...

No, you have to have a saved model before creating the property bag. It uses model relationships and those relationships can't exist without the model ID, which is created after saving. Doing otherwise would basically be a package re-write.