Reputation: 258
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
Upvotes: 1
Views: 3151
Reputation: 6233
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'];
}
Upvotes: 2
Reputation: 149
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');
}
Upvotes: 0