Originally posted @ https://codeanddeploy.com visit and download the sample code:
In this post, I will show you an example of the Laravel model create with different methods that can use in your application. When learning the Laravel model creating or inserting records in your database is one of the important learning.
In this example, we are using query builder to insert records into our database. We are using the DB facade for this method. See the example code below.
$user = DB::table('users')->insert([ 'name' => 'Juan Dela Cruz', 'email' => 'firstname.lastname@example.org', 'password' => bcrypt('password') ]); //return to true
In this example, we are using Eloquent with a long-hand method using s
ave() function: See below example code:
$user = new \App\Models\User(); $user->name = "John Doe"; $user->email = "email@example.com"; $user->password = bcrypt('password'); $user->save();
In this example, we will use the Eloquent
create() method which passes the array values.
\App\Models\User::create([ 'name' => 'Jane Dane', 'email' => 'firstname.lastname@example.org', 'password' => bcrypt('password') ]);
In this example, this will be a quicker way of saving records in Laravel Eloquent by creating a PHP instance but not yet recorded in our database. We need to call the
save() method to do it.
$user = new \App\Models\User([ 'name' => 'Jane Dane', 'email' => 'email@example.com', 'password' => bcrypt('password') ]); $user->save(); //returns true
Thank you for reading the Laravel model create. I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-model-create-example if you want to download this code.
Happy coding :)