Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert current date time using laravel

I want to store the current date time in MySQL using the following Laravel function. Actually, I stored a static date. Instead of this, how can I store the current date time in the created_at and updated_at fields in the database?

function insert(Request $req)
{
    $name = $req->input('name');
    $address = $req->input('address');
    $data = array("name" => $name, "address" => $address, "created_at" => '2017-04-27 10:29:59', "updated_at" => '2017-04-27 10:29:59');
    DB::table('student')->insert($data);
    echo "Record inserted successfully.<br/>";
    return redirect('/');
}
like image 847
seema Avatar asked Dec 13 '18 04:12

seema


People also ask

How to add current date in laravel?

Using Carbon to get the current date and time php use Carbon\Carbon; Then you will be able to use all of the handy methods that Carbon provides. In some cases, you might want to output the current date directly in your Blade template.

How to store date in database laravel?

Database should be always YYYY-MM-DD; Laravel back-end: in forms/views we should have whatever format client wants, but while saving to database it should be converted to YYYY-MM-DD; JavaScript datepicker: JS formats for dates are not the same as PHP formats, we will see that below in the example.


2 Answers

Use the Laravel helper function

now()

Otherwise, use the carbon class:

Carbon\Carbon::now()

It is used like this:

$data = array("name" => $name,"address" => $address,"created_at"=> Carbon::now(),"updated_at"=> now());
DB::table('student')->insert($data);

For more information, see now()

like image 160
Jignesh Joisar Avatar answered Oct 20 '22 01:10

Jignesh Joisar


You can also use this to get the current date time. It's working.

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

And also I have updated and set things in your function. You have to add this:

function insert(Request $req)
{
    $name = $req->input('name');
    $address = $req->input('address');

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

    $data = array("name" => $name,
                  "address" => $address,
                  "created_at" => $current_date_time,
                  "updated_at" => $current_date_time);
    DB::table('student')->insert($data);
    echo "Record inserted successfully.<br/>";
    return redirect('/');
 }
like image 3
dhara gosai Avatar answered Oct 20 '22 03:10

dhara gosai