The Insert and create statement in Laravel.

Insert and create statement in Laravel

Insert Statements: Insert method that may be used to insert records into the database table. The insert method accepts an array of column names and values: for example

DB::table('users')->insert(
 'email' => 'kayla@example.com',
 'votes' => 0
]);


Create Statement: The create method to "save" a new model using a single PHP statement. for example:


use App\Models\User;
$user = User::create([
  'email' => 'kayla@example.com',
  'votes' => 0
]);


so, in the above functions both insert and create statement doing the same work, means both stores the user data in the database.


then where is the difference?πŸ€”


I am going to explain it briefly


 when we are migrating a table and used created_at,updated_at column in that table. at the time of insert a new row, we have to pass the value of the column if the data type is not null. for example:

DB::table('users')->insert([
   'email' => 'kayla@example.com',
   'votes' => 0,
   'created_at'=>date("Y-m-d"),
   'updatede_at'=>date("Y-m-d")
]);

when we user the create function we no need to pass the created_at and updated_at value .like

use App\Models\User;
DB::table('users')->insert([
  'email' => 'kayla@example.com',
   'votes' => 0,
]);


it stores the value for created_at,updated_at  automatically. because this function used the User Model. In laravel model there are lots of inbuild functions are already available, for storing created_at and updated_st the timestamps value is true in default.


so, from all this above discussion we get a conclusion that when we use a model to insert data in the database, we should use the create function because using this create function we can access the function which is already available in the model.


and when we access the database directly, without using the model concept. we can use the insert method.




                                          If you find it is useful please comment and share itπŸ‘πŸ˜Š


thank you.






Comments

Post a Comment