toto01
toto01

Reputation: 153

Insert Date and time in dataBase using Laravel 5.4

I want to insert Date of the current day and time, here is my code :

$test = new Test;

$dt = new DateTime;

$test->date = $dt->format('m-d-y H:i:s');
$test->users_id = Auth::user()->id;
$test->save();

the problem is that it does not fit the correct date in database, it insert :

2007-02-18 09:52:41

Upvotes: 1

Views: 9648

Answers (1)

Saiyan Prince
Saiyan Prince

Reputation: 4020

Why you want to store it in a custom format which is not defined in your database? Wrong idea in my opinion.


Proper solution according to me:

I'll make an assumption that you are storing the date and time in MySQL database as TimeStamp value with a default value of null. Something like this:

$table->timestamp('your-date-column')->nullable();

When hitting the controller method:

public function yourControllerMethod(Request $request)
{
    // Don't forget to import the Carbon namespace
    $dateTime = Carbon::parse($request->your_datetime_field);

    $request['your_datetime_field'] = $dateTime->format('Y-m-d H:i:s');
}

When retrieving the your_datetime_field, parse it as Carbon instance by default using like this:

Test.php

/**
 * The dates that will be mutated to Carbon instance.
 *
 * @return  array
 */
protected $dates = [
    'your_datetime_field',
];

Now that you have converted the field into Carbon instance on runtime, you are free to edit the date and time format as per your requirement.


Not a proper solution:

Warning, I have not tested this, but I guess it should work..

If you still want to save it as a custom format in the database field, save it as a string format with a default value of null.

$table->string('your-date-column')->nullable();

And then cast it to datetime type at the runtime.

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'your_datetime_field' => 'datetime:Y-m-d',
];

Again, I would recommend not to go in the wrong direction unless you know what you are doing and what are the consequences.

You get the idea.

Upvotes: 4

Related Questions