5

I would like to know how it is possible to merge data from Input::all() with a model and save the result.

To clarify: I would like to do something like below:

$product = Product::find(1); // Eloquent Model

$product->merge( Input::all() ); // This is what I am looking for :)

$product->save();
Cy Rossignol
  • 16,216
  • 4
  • 57
  • 83
user3518571
  • 407
  • 2
  • 5
  • 11

4 Answers4

4

You should use update method:

$product->update(Input::all());

But I recommend to use only method instead

$product->update(Input::only('name', 'type...'));
Razor
  • 9,577
  • 3
  • 36
  • 51
  • Thank you! Just tried it out but passing the data to save() does (unfortunately) not save anything :/ Did you try this? – user3518571 Jun 12 '14 at 09:51
  • If you instantiate a new model: `$product = new Product;` you can use the `save` method. – Razor Jun 12 '14 at 10:20
  • You can use `all()` method when you declare `protected $fillable = ['field_1', 'field_n'];` in your model. Then only these columns are being mass-assigned and no additional fields an attacker may have added. See @cy-rossignol answer. – Roland Jul 09 '18 at 08:54
4

Use the model's fill() method for greater control. This lets us change attributes after merging the values before we save:

$product->fill($request->all());
$product->foo = 'bar';
$product->save();

If we've properly defined the model's $fillable attributes, there's no need to use Input::only(...) (or $request->only(...) in newer versions).

Cy Rossignol
  • 16,216
  • 4
  • 57
  • 83
0

In addition to Razor's answer, if you need to create a new model you can use:

$product = Product::create(Input::all());
Ricardo Metring
  • 401
  • 4
  • 7
0

I think the better way now is to use FormRequest and the validated function like this :

public function update(Product $product, ProductFormRequest $request)        
    {
        $product->update($request->validated());
        //...
    }