Inserting the current date and time into a Laravel database is a fundamental need to keep track of when records are created or updated. This tutorial covers some common methods and provides examples for inserting the current date and time into a Laravel database.
Laravel get and insert the current date time into the database; In this tutorial, you will learn how to get and insert date time into database using carbon, date(), and DateTime() in laravel.
How to Insert Current Date and Time into Database in Laravel
Below are some methods to insert current date and time into database in laravel:
- Method 1 – Using Carbon
- Method 2 – Using date()
- Method 3 – Using dateTime()
Method 1 – Using Carbon
To insert the current date and time in Laravel, you can use the carbon::now() method. Here is example:
use Carbon\Carbon;
// ...
public function insertUsingCarbon()
{
$currentDateTime = Carbon::now();
// Assuming you have a model and a column named 'created_at'
YourModel::create(['created_at' => $currentDateTime]);
// Or if you want to update an existing record
$yourModel = YourModel::find($id);
$yourModel->update(['created_at' => $currentDateTime]);
}
Method 2 – Using date()
Using php date() function, you can insert the current date and time in Laravel. Here is example:
public function insertUsingDate()
{
$currentDateTime = date('Y-m-d H:i:s');
// Assuming you have a model and a column named 'created_at'
YourModel::create(['created_at' => $currentDateTime]);
// Or if you want to update an existing record
$yourModel = YourModel::find($id);
$yourModel->update(['created_at' => $currentDateTime]);
}
Method 3 – Using dateTime()
Using php new DateTime() function, you can insert the current date and time in Laravel. Here is example:
public function insertUsingDateTime()
{
$currentDateTime = new DateTime();
// Assuming you have a model and a column named 'created_at'
YourModel::create(['created_at' => $currentDateTime]);
// Or if you want to update an existing record
$yourModel = YourModel::find($id);
$yourModel->update(['created_at' => $currentDateTime]);
}
Conclusion
That’s it; you have learned how to get and insert date time into database using carbon, date() and DateTime() in laravel.