Table of contents

laravel model create

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.

 

Example #1: Basic insert using Query Builder

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' => 'dcruz@gmail.com',
    'password' => bcrypt('password')
]);

//return to true

 

Example #2: Basic Long-Hand Method

In this example, we are using Eloquent with a long-hand method using save() function: See below example code:

$user = new \App\Models\User();
$user->name = "John Doe";
$user->email = "jdoe@gmail.com";
$user->password = bcrypt('password');
$user->save();

 

Example #3: Basic with Laravel Model Create

In this example, we will use the Eloquent create() method which passes the array values.

\App\Models\User::create([
    'name' => 'Jane Dane',
    'email' => 'jdane@gmail.com',
    'password' => bcrypt('password')
]);

 

Example #4: Quicker Method

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' => 'jdane2@gmail.com',
    'password' => bcrypt('password')
]);

$user->save(); //returns true

 

Thank you for reading the Laravel model create. I hope this is helpful to your application.