0

I am trying to save a date from jQuery UI datepicker to database.

I want to display the date in m/d/Y format on date selection from the input form.

When I try to save it to the database, it is giving the following error: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value

I have followed a lot of solutions, however it is not working for me.

I have looked through this link, though I followed everything correctly, it is still returning the same error.

Controller Code

    public function store(Request $request)
    {
        $user = Frontend::create($request->all());
    }

Model Code

class Frontend extends Model
{
    use HasFactory;

    protected $table = 'frontend';

    protected $fillable = ['date'];

    public function setDateAtttribute($date)
    {
        $this->attributes['date'] = Carbon::createFromFormat($date)->format('Y-m-d');
    }
}

config>app.php

'date_format' => 'm/d/Y',
'date_format_javascript' => 'mm/dd/yy',

I am new to this and it would be a huge help if anyone could help me find the solution.

Reman Bala
  • 97
  • 1
  • 3
  • 9

4 Answers4

1

Have you tried this method

$this->attributes['date'] = date("Y-m-d",strtotime($data));
Waqas Mustafa
  • 192
  • 1
  • 7
1

Well, first of all, Carbons createFromFormat method take 2 arguments. Carbon::createFromFormat($format, $time)

If you define $dates property on your model like:

class Frontend extends Model {

    protected $dates = [
        'date',
    ];
}

Then you dont have to worry about formatting, you just pass a Carbon instance to $date property. Eloquent should automatically save in correct format. Plus when any record is retrieved, your $date will be Carbon instance as well.

Lukáš Moravec
  • 189
  • 2
  • 8
1

Here's one specific for your js code :

$('#datepicker').datepicker({ 
   dateFormat: 'Y-m-d',
});
STA
  • 30,729
  • 8
  • 45
  • 59
0

You need to change under setDateAtttribute() public function setDateAtttribute($date) { $this->attributes['date'] = Carbon::parse($date); }

Swati
  • 64
  • 2