I'm trying to setup a simple form to save, but want to be sure we are using best practices, like DI.
In the controller file, I have
public function store()
{
//get form data
$data = Input::all();
$newclient = new Client($data);
$newclient->save();
return Redirect::route('clients.index');
}
But that really isn't dependency injection. (right?) I injected the model like this
public function __construct(\Client $clientmodel)
{
$this->clientmodel=$clientmodel;
}
How would I save the form data on the store function properly, using dependency injection?
Looking at the __constructor
in Illuminate\Database\Eloquent\Model
you can see it uses fill()
to assign the passed in values.
public function __construct(array $attributes = array())
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
So you can just use fill()
to do the same after the class has been instantiated:
$this->clientmodel->fill($data)
$this->clientmodel->save();
Or if you want to just save it anyways, you can use create()
:
$this->clientmodel->create($data);
If you are always creating a new object then you can use the Eloquent Model's create
method like so:
public function store()
{
//get form data
$data = Input::all();
$this->clientmodel->create($data);
return Redirect::route('clients.index');
}
If it's possible that sometimes this route will be handling updates of an existing Client
record then you should take a look at the firstOrCreate
and firstOrNew
methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With