1

I'm New in Laravel;

I'm Using Data Packer Jquery and it output like this format:

14-Aug-2019

I tray to save it in database by this code:

if ($request -> isMethod('post')) {
        $data = $request -> all();
        $course = new Courses;
        $course -> start_date = $data['start_date'];
        $course -> save();
        return redirect('/admin/courses');
    }

But i found this error:

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '14-Aug-2019' for column 'start_date' at row 1

Ramy Mohamed
  • 236
  • 1
  • 5
  • 18
  • 1
    Possible duplicate of [Invalid datetime format: 1292 Incorrect datetime value](https://stackoverflow.com/questions/42490101/invalid-datetime-format-1292-incorrect-datetime-value) Please take a look here, it should be helpful to you :) – Watercayman Aug 31 '19 at 17:17
  • try `$course->start_date = new \Carbon\Carbon($data['start_date']);` – dparoli Aug 31 '19 at 17:36

2 Answers2

2

MySQL expects date to be like 2019-08-14 and you are trying to save 14-Aug-2019. So you are getting the error. You can solve it either by sending the exact formatted date from the front end or parse it in the back end.

Send Y-m-d value from the datepicker

$( "#date" ).datepicker({
   dateFormat: 'yy-mm-dd',
});  

It will send date like 2019-08-14 and you can save it directly.

If you want to use format like 14-Aug-2019 then you have to parse it using Carbon so that you can save it in the database.

use Carbon\Carbon;
$date = '14-Aug-2019';
$d = Carbon::parse($date)->format('Y-m-d'); //return date 2019-08-14

Cast your start_date as a date in your model. It will help you to format it anyway you want.

class Courses extends Model
{
    protected $dates = ['start_date'];
} 
zahid hasan emon
  • 6,023
  • 3
  • 16
  • 28
0

Hope it will for for you

    if ($request -> isMethod('post')) {
        $data = $request -> all();
        $course = new Courses;
        $course -> start_date = STR_TO_DATE($data['start_date'], '%d-%M-%Y');
        $course -> save();
        return redirect('/admin/courses');
    }
Vikas Verma
  • 149
  • 1
  • 11