insert

How to Insert Records Using Laravel Eloquent?

There are two main ways to insert a record in database using Laravel eloquent. First we can initialise a new instance of Model class and set properties manually one by one then we can call save() method on that. Here is the code,

$contact = new Contact;
$contact->name = "Jonathan Archer";
$contact->email = "[email protected]";
$contact->phone_number = "+1-402-266-2488";
$contact->save();

Or this code will have same effect.

$contact = new Contact( [
	"name"         => "Jonathan Archer",
	"email"        => "[email protected]",
	"phone_number" => "+1-402-266-2488",
] );

$contact->save();

We can also add record using save() method in another way.

$contact = Contact::make( [
	"name"         => "Jonathan Archer",
	"email"        => "[email protected]",
	"phone_number" => "+1-402-266-2488",
] );

$contact->save();

Now remember if you will not call save() then instance will remain in program until its running but it will not be saved in database. It will not have id attached to it. If we do not want to use  save() then we can simple do this.

Contact::create( [
	"name"         => "Jonathan Archer",
	"email"        => "[email protected]",
	"phone_number" => "+1-402-266-2488",
] );

If you have any questions please leave a comment. We really appreciate that.