be-codified
be-codified

Reputation: 6124

Laravel Eloquent: inserting data

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.

Upvotes: 5

Views: 66896

Answers (4)

Emmanuel Iyen
Emmanuel Iyen

Reputation: 439

DB::table('nodes')->insertGetId(
  [
    'name' => $name,
    'walletaddress' => $wallet,
    'datecreated' => '11'
  ]
);

Upvotes: 1

lukasgeiter
lukasgeiter

Reputation: 152900

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

Upvotes: 21

Poncho
Poncho

Reputation: 746

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.

Upvotes: 2

Phi Nguyen
Phi Nguyen

Reputation: 3056

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.

Upvotes: 8

Related Questions