Laravel 5: creating new models in controllers
What's the correct way to create new models in Laravel 5 controllers? I don't want to use the model class names directly, but instead I insert them into the controller constructor, like this:
public function __construct(User $user) {
$this->user = $user;
// ...
}
To work with the user model, I would normally use the controller property, for example:
$target = $this->user
->women()
->whereBetween('age', [18, 29])
->get();
But how can I create a new model using $this->user
? I usually prefer to use new User;
and assign properties and then use $user->save();
. But that's pretty impossible, isn't it? I know there is a method create()
that will work in this case, for example:
$girl = $this->user->create([
'name' => 'Jessica Hottie',
'age' => 21
]);
But this way I lose the ability to use the method associate()
etc.
Should I be using create()
anyway, or perhaps an even better way to handle model dependencies?
source to share