0

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?

4

2 回答 2

2

这应该有效。如果它们尚未传入,它只会应用默认值。我还将默认值设置为常量,因此如果您稍后需要修改它们,它们很容易找到。

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);
}
于 2017-05-24T17:15:19.317 回答
0

你能行的

new Window($request->all());
// Or
new Window($request->only(['foo', 'bar']));
// Or immediately create the instance
Window::create($request->all());

但是您应该首先将所需的属性添加到模型中的$fillable属性中Window

class Window extends Model {
    protected $fillable = ['foo', 'bar'];
}
于 2017-05-24T17:20:40.003 回答