Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to save form data in Laravel (using an injected model)?

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?

like image 937
hdwebpros Avatar asked Feb 12 '23 01:02

hdwebpros


2 Answers

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);
like image 161
lukasgeiter Avatar answered Feb 13 '23 20:02

lukasgeiter


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.

like image 37
nCrazed Avatar answered Feb 13 '23 21:02

nCrazed