Basically let's say I have a model named 'Window'. I know laravel provides created event for new instances of the model, the problem is I don't always first create new database records so that the method is called, but I sometimes need to create an instance of the facade first. What I mean:
$window = App\Window::create(); //this creates a new record in the
//database and the 'created' event is being called in laravel,
//so I can assign some properties. Everything is ok
$window = new App\Window;//but this only creates an instance of the facade
//which is not being saved until `$window->save();` is called.
The ting is that in my code so far I've avoided directly creating new empty records in the database, so I've used the second method. But now I'd like to handle that creation of new App\Window
in order to assign custom default properties for each window programatically. Is there a way to achieve it?
This should work. It will only apply defaults if they aren't already passed in. I also set the default values up as constants so if you need to modify them later, they are easy to find.
const COLUMN_DEFAULT = 'some default';
const SOME_OTHER_COLUMN_DEFAULT = 'some other default';
public function __construct(array $attributes = [])
{
if (! array_key_exists('your_column', $attributes)) {
$attributes['your_column'] = static::COLUMN_DEFAULT;
}
if (! array_key_exists('some_other_column_you_want_to_default', $attributes)) {
$attributes['some_other_column_you_want_to_default'] = static::SOME_OTHER_COLUMN_DEFAULT;
}
parent::__construct($attributes);
}