Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto map data from Request to Model in Laravel 5.5


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?

like image 987
Thanh Dao Avatar asked Dec 11 '17 03:12

Thanh Dao


2 Answers

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' ...]);
like image 54
Mathew Tinsley Avatar answered Sep 30 '22 10:09

Mathew Tinsley


  • 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.

like image 33
Muhammad Sadiq Avatar answered Sep 30 '22 10:09

Muhammad Sadiq