简体   繁体   中英

passing an array from controller to model in laravel

I want to know that how to pass an array from laravel controller to laravel model .So that i can save them into db using a model . I don't want to make my controllers to heavy for that I am asking for this . When I have been saving form submissions into db where I should put my saving function ? in controller or model?

Laravel has something called Mass Assignment . It let's you pass an associative array and fills the model with those values. To make it work you have to define all the attributes you want to be able to mass assign in your model:

protected $fillable = ['foo', 'bar', 'and', 'much', 'more'];

Now you can just pass an array to the constructor of the model:

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

$model = new Model($input);
$model->save();

Or even shorter, use the create() method which fills the model and directly saves it afterwards:

Model::create($input);

Try this..

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM