Laravel雄辩:合并模型与输入

问题描述:

我想知道如何将Input::all()的数据与模型合并并保存结果。Laravel雄辩:合并模型与输入

为了澄清:我想这样做如下:

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

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

$product->save(); 

您应该使用update方法:

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

但我建议使用only方法,而不是

$product->update(Input::only('name', 'type...')); 
+0

谢谢!只是试了一下,但传递数据save()(不幸)没有保存任何东西:/你试过这个吗? – user3518571

+0

你是对的,回答更新 – Razor

+0

如果你实例化一个新模型:'$ product = new Product;'你可以使用'save'方法。 – Razor

除了Razor的回答,如果你需要创建一个新的模型y ou可以使用:

$product = Product::create(Input::all()); 

使用该模型的fill()方法进行更好的控制。这让我们合并值之前我们保存后更改属性:

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

如果我们已经properly defined模型的$fillable属性,没有必要(在较新的版本或$request->only(...))使用Input::only(...)