I would like to submit my form with many of fields.
As the documentation
$flight = new Flight;
$flight->name = $request->name;
$flight->param1 = $request->param1;
$flight->param2 = $request->param2;
...
$flight->param_n = $request->param_n;
$flight->save();
Its a bad idea if have too much fields.
I'm looking for any script like:
$flight = new Flight;
$flight->save($request->all());
But $request->all()
function got unnecessary fields
What is the best way to do?
You could use the model $fillable
array for this so long as your model properties match your request properties exactly.
$flight = new Flight();
$data = $request->only($flight->getFillable());
$flight->fill($data)->save();
You'll need to specify the fillable fields for any model that you would like to use this behavior for.
For Laravel 5.4 and lower use intersect
instead of only
Otherwise you can just whitelist the properties you want from the request
$data = $request->only(['param1', 'param2' ...]);
There are various ways. you can exclude unwanted values as
$data = $request->except(['_token','_method','etc']);
The best way would be validated data. viz apply validation on your form inputs on server side.
$validated_data = $request->validate(['field1'=>'required','field2'=> 'required']);
etc. you can apply desired validations on each field and only validated fields will be in $validated_data variable, and then you can save them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With