Unexpected data found during save on eloquent / Laravel
Asked Answered
R

4

14

I have one more field on the database over the created_at and updated_at as TIMESTAMP the field name is date.

So i overwritten the method getDates() on my model eloquent because i wanted that field be instantiated from Carbon.

public function getDates()
{
   return ['date','created_at','updated_at'];
}

But when i go to create a new record on the database it throw me an exception:

InvalidArgumentException Unexpected data found. Unexpected data found. Unexpected data found.

Ps: the value sent from the form is in EU format: d-m-Y h:i

I don't know how figure out this problem any suggestion are appreciated

Rosalynrosalynd answered 13/4, 2014 at 12:17 Comment(1)
You have the solution in my answer now.Matteroffact
M
14

You array returned from getDates was merged with the dafault one resulting in:

['created_at','updated_at','deleted_at','date','created_at','updated_at'];

so use only 'date' there and should be fine.


Try setting up a mutator for 'date' to convert the data from input into timestamp format. The error you get is not on Eloquent but Carbon.

public function setDateAttribute($value)
{
    $this->attributes['date'] = Carbon\Carbon::createFromFormat('d-m-Y h:i', $value);
}

Also there is mistake in the docs, as getDates defines date accessors, not mutators..

Matteroffact answered 13/4, 2014 at 12:25 Comment(4)
Tried but seem not be this one the problem thanks. Anyway is not merged but is overwritten.Rosalynrosalynd
Yes, my bad. I just now realized what the problem is. Check the edit.Matteroffact
Yes this is the right answer i tried on this way for see if it work and it does. :) Thanks mate.Rosalynrosalynd
If you are modifying format of any date then use alias name like DB::raw('(case when backup_records.created_at IS NOT NULL then date_format(backup_records.created_at, "%d-%m-%Y %h:%i:%s %p") else "Not Available" end) as created_at_text') instead of 'created_at'.Portwin
S
1

Try this:

Carbon::createFromFormat('d.m.Y H:i', $request->publishdate);    
Soninlaw answered 24/10, 2016 at 12:8 Comment(0)
M
0

You can't use your format "d-m-Y h:i"

You must use one of those: UNIX timestamp, date string (Y-m-d), date-time string, DateTime / Carbon instance

https://laravel.com/docs/4.2/eloquent#accessors-and-mutators

Matthews answered 6/1, 2016 at 14:37 Comment(0)
S
-1

Even though its a year old issue and I'm placing my input for anyone still struggling even after setting the mutator.

If the html input date element passes the date in atom format(1975-12-25T14:15:16-05:00) then the date mutator won't help. You need to apply the following fix in Illuminate\Database\Eloquent\Model class at line#2848 to get it work (in laravel#5).

$value = Carbon::createFromFormat($format, (new DateTime($value))->format('Y-m-d H:i:s'));
Snubnosed answered 23/3, 2015 at 6:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.