5

I am sending a bunch of data through post method. For now I am using a fully working solution:

$dataClient = new Client;
$dataClient->name    = $post['client']['name'];
$dataClient->address = $post['client']['address'];
...
$dataClient->save();        

I am wondering if there is a shorter solution? Like posting an array and Laravel could map keys to db fields?

What if you would add something more, like calculated value upon?

Example:

$dataClient = new Client;
Then map array keys to db keys
$dataClient->someField = someCalculatedValue 
$dataClient->save();

Thank you in advance.

be-codified
  • 5,704
  • 18
  • 41
  • 65

4 Answers4

20

You have quite a few options when it comes to creating models from a data array. If you want to directly insert it into the database, the easiest way is create()

Client::create($post['client']);

If you want to change some things afterwards or just not save it right away, just pass your data to the constructor.

$client = new Client($post['client']);
$client->someField = 'some value';
$client->save();

And finally, the last option, calling fill() manually. This method is used internally for create() as well as in the constructor.

$client = new Client();
$client->fill($post['client']);
$client->save();

Note: for all methods above you'll need to set up the fillable attributes in your model. This is to protect against malicious user input (request data).

protected $fillable = ['name', 'address', 'etc'];

More information about Mass Assignment

lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • lukasgeiter thank you for your answer. Can you give me another example for mass assignment vulnerability? – be-codified Jul 02 '15 at 08:52
  • 1
    Here's a simple one: let's say you have a field `is_admin`. Now you would pass the request data right to the model and it would just save all the values anybody could make themselves admin just by manipulating the request data and adding `is_admin=1` – lukasgeiter Jul 02 '15 at 08:58
8

Eloquent has create and update methods which will insert massive data. For example :

inputs = ['name' => 'value','address' => 'value'];
Client::create(inputs)

It will automatically map fields in Eloquent.

Phi Nguyen
  • 3,046
  • 14
  • 26
2

Have you tried something like this?

$dataClient = new Client;
$dataClient->fill($client);
$dataClient->save();

Depending on how you set up your Client model and what fields you set as guarded/fillable, the fill method will automatically map the data with their respective fields.

Poncho
  • 746
  • 1
  • 6
  • 12
1
DB::table('nodes')->insertGetId(
  [
    'name' => $name,
    'walletaddress' => $wallet,
    'datecreated' => '11'
  ]
);
Tyler2P
  • 2,324
  • 26
  • 22
  • 31