在Laravel中动态保存表单字段

时间:2017-03-18 17:17:44

标签: php laravel

我有一个包含大量输入的表单。我不想一个接一个地拿到它们。我正在考虑将它们放在一个循环中,或者某种东西。所以不要写这个:

$page = new Pages(); //my model
$page->title = $request->input('title');
$page->url_name = $request->input('url_name');
$page->category_id = $request->input('category_id');
$page->page_cols = $request->input('page_cols');
//.......... 30 more 
$page->save();

我在考虑使用循环:

 foreach ($request->input() as $key => $value) {
   if ($key != "_token"){
   // assign them to the $page
   }
 }
 $page->save

但我不知道该怎么做。如果您有任何想法,请与我分享。谢谢!

4 个答案:

答案 0 :(得分:2)

您可以使用create方法将新模型保存在一行中作为 -

Pages::create(Input::all());

在您的Pages模型中添加$fillable属性,该属性可以帮助您避免在用户通过请求传递意外HTTP参数时发生的批量分配漏洞,并且该参数会更改您没想到的数据库。

例如 -

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['name'];

或者您可以使用与$guarded

相反的$fillable
/**
 * The attributes that aren't mass assignable.
 *
 * @var array
 */
protected $guarded = ['id'];

Docs

答案 1 :(得分:0)

你可以使用它:

Pages::create(Input::all());

要排除令牌使用:

Input::except('_token')

您需要填写属性protected $fillable以进行批量分配。您可以在文档中阅读更多相关信息: https://laravel.com/docs/5.4/eloquent#mass-assignment

您可以添加protected $ guarded = [];到你的模型。这使得所有字段都可以分配。

答案 2 :(得分:0)

Pages::create(Input::except('_token'));

答案 3 :(得分:0)

Pages::create(Input::all());可以解决问题。

它基本上是质量分配,因此您必须将DB表字段分配给相关模型中的protected $fillable = []数组。

与此相反的是protected $guarded = [];

如果没有令牌:Input::except('_token')