How To Insert Current Datetime In Database Laravel

  • 06-06-2022
  • 1048
  • Laravel 9
  • Haresh Chauhan

This is most important when you insert data into the database current time and date where the record insert into the database.

If you are using an eloquent model then it will take the default current time and date in created and updated at column.

Instead of current_at and updated_at column, If you want to insert datetime into the database function now() carbon will help you to insert current date time into the database.

So in this post, you will learn how to insert current database time into the database with examples.

Example 1: Using now()

In this example data inserted into user table using now() carbon function.

\DB::table('users')->insert([
    'name' => Str::random(10),
    'email' => Str::random(5).'@gmail.com',
    'password' => bcrypt('123546'),
    'created_at' => now(), // On create current time insert
    'updated_at' => now() // On create current time insert
]);

You can also use carbon.

use \Carbon\Carbon;

\DB::table('users')->insert([
    'name' => Str::random(10),
    'email' => Str::random(5).'@gmail.com',
    'password' => bcrypt('123546'),
    'created_at' =>  Carbon::now(),
    'updated_at' => Carbon::now(),
]);

Example 2: Using date()

In this example, data is inserted into the user table using date() the PHP function with the given specific format.

$current_date = date('Y-m-d H:i:s');

\DB::table('users')->insert([

    'name' => Str::random(10),
    'email' => Str::random(5).'@gmail.com',
    'password' => bcrypt('123546'),
    'created_at' => $current_date,
    'updated_at' => $current_date
]);

Example 3: Using DateTime()

In this example inset the current date and time into database using DateTime() class.

$curTime = new \DateTime();

\DB::table('users')->insert([

    'name' => Str::random(10),
    'email' => Str::random(5).'@gmail.com',
    'password' => bcrypt('123546'),
    'created_at' => $curTime->format("Y-m-d H:i:s"),
    'updated_at' => $curTime->format("Y-m-d H:i:s")
]);

Thanks...


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :