Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在laravel中将数组从控制器传递到模型_Laravel - Fatal编程技术网

在laravel中将数组从控制器传递到模型

在laravel中将数组从控制器传递到模型,laravel,Laravel,我想知道如何将数组从laravel控制器传递到laravel模型,以便使用模型将它们保存到db中。我不想让我的控制器太重,因为这是我的要求。当我将表单提交保存到db中时,我应该将保存功能放在哪里?在控制器或模型中?试试这个 //In Model get data from controller public function functionname($data1, $data2){ //query } //In Controller sent data to Model $data

我想知道如何将数组从laravel控制器传递到laravel模型,以便使用模型将它们保存到db中。我不想让我的控制器太重,因为这是我的要求。当我将表单提交保存到db中时,我应该将保存功能放在哪里?在控制器或模型中?

试试这个

//In Model get data from controller
public function functionname($data1, $data2){
    //query
}


//In Controller sent data to Model
$data = Modelname::functionname($data1, $data2)->get();

拉威尔有一个名字叫。它让您传递一个关联数组,并用这些值填充模型。要使其正常工作,您必须定义要能够在模型中批量指定的所有属性:

protected $fillable = ['foo', 'bar', 'and', 'much', 'more'];
现在,您可以将数组传递给模型的构造函数:

$input = [
   'foo' => 'value1',
   'bar' => 'value2',
   'and' => 'value3',
   'much' => 'value4',
   'more' => 'value5',
];

$model = new Model($input);
$model->save();
甚至更短,使用
create()
方法填充模型,然后直接保存:

Model::create($input);

是的,我知道这个$gurded,$filled的东西。但是我想把save()方法放到模型中,
save()
方法在模型中。。。如果您的意思是希望在模型内检索用户输入,那么这是一种糟糕的做法。模型只是数据层,不必担心从何处获取数据。
Model::create(Input::all())
有什么不好的地方?好的。知道了。谢谢卢卡斯盖特,不客气。如果解决了你的问题,请考虑这个答案: