Laravel / Model / Save data into DB
Insert data into table
-
STEP
Function Syntax Example Note create() Model_Name::create($array_value); User::create( ['name'=>'manoj', 'email' => 'keval@example.com'] ); 1. Static operator ::
2. array parameter in create();
3. Allows one record at a time
4. return the ID of the inserted record
5. automatically sets the created_at and updated_at timestampsinsert() Model_Name::insert($array_value); User::insert( ['name'=>'manoj', 'email' => 'keval@example.com'] );
OR User::insert( ['name'=>'manoj', 'email' => 'keval@example.com'], ['name'=>'sreehari', 'email' => 'keval@example.com'] );1. Static operator ::
2. array parameter in insert();
3. Allows multiple records at a time
4. does not return the ID of the inserted record
5. does not set the created_at and updated_at timestampssave() Object_Name->save(); $user = new User;
$user->name = $request->name;
$user->save();1. object operator ->
2. no function parameters
3. assign the data to object parametersfirstOrCreate() Model_Name::firstOrCreate($array_conditions, $array_value); $user = User::firstOrCreate(
['name' => 'manoj'],
['email' => 'email@example.com', 'mobile' => '9847']
);1. Static operator ::
2. Two function parameters 3. First parameter is an array used for where condition
4. Second parameteris an array used for updating or creatingfirstOrNew() Model_Name::firstOrNew($array_conditions, $array_value); $user = User::firstOrNew(
['name' => 'manoj'],
['email' => 'email@example.com', 'mobile' => '9847']
); $user->save();1. Static operator ::
2. Two function parameters 3. First parameter is an array used for where condition
4. Second parameteris an array used for updating or creatingupdateOrCreate() Model_Name::updateOrCreate($array_conditions, $array_value); $flight = User::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99, 'discounted' => 1] );1. Static operator ::
2. Two function parameters 3. First parameter is an array used for where condition
4. Second parameteris an array used for updating or creating1. create()
Eloquent create() method which passes the array values.
\App\Models\User::create([ 'name' => 'Jane Dane', 'email' => 'jdane@gmail.com', 'password' =>'123' ]); Create() allows only one record at a time 2. insert()
Eloquent insert() method which passes the array values.
\App\Models\User::insert([ 'name' => 'Jane Dane', 'email' => 'jdane@gmail.com', 'password' =>'123' ]); insert() allows multiple records at a time 3. save()
Eloquent save() using attributes.
$user = new \App\Models\User(); $user->name = "John Doe"; $user->email = "jdoe@gmail.com"; $user->password = '2312312'; $user->save(); No parameters pass to function save()