Json column - Date field must cast to 'date' in Eloquent model - php

I have a laravel nova panel like below. Im trying to use a Date field like below:
new Panel('Suggestions', [
Flexible::make('Suggestions')
->addLayout('Suggestions', 'suggestion', [
Text::make('Title'),
Textarea::make('Message'),
Date::make('Date', 'date')
])
->button('Add Suggestion'),
]),
However it shows this error:
{message: "Date field must cast to 'date' in Eloquent model.", exception: "Exception",…}
exception: "Exception"
file: "/var/www/html/vendor/laravel/nova/src/Fields/Date.php"
line: 41
message: "Date field must cast to 'date' in Eloquent model."
I have in the model the casts property like this:
protected $casts = [
'date' => 'date'
];
Do you know what can be the issue?
I don't have a date field on the database table relative to the model. I just have a suggestions json field that has a lot of columns including the "date" column/key, probably that's the issue. Do you know how to solve this issue in this scenario? Thanks

Add this to your casts instead of 'date' => 'date', this solved for me the issue.
protected $casts = [
'flexible-content' => FlexibleCast::class
];
Another options is resolving it and converting it to a MomentJS format which also works fine:
DateTime::make('Date')
->format('DD/MM/YYYY HH:mm')
->resolveUsing(function ($value) {
return $value;
}),
source: https://github.com/whitecube/nova-flexible-content/issues/171

First, I guess you need to rename your db field to something else.
And then
You need to cast your db field into your model like this:
//Casts of the model dates
protected $casts = [
'DB_FIELD_NAME' => 'date'
];

Related

Laravel 5.1 - Date Validation & Attribute casting

My model has the following validation and rules :
public $rules = [
'hire_date' => 'date|required|required_with:dismiss_date',
OR
'hire_date' => 'date_format:"Y-m-d"...',
];
protected $casts = [
//'hire_date' => 'date' ,
'dismiss_date' => 'date' ,
];
// Or
protected $dates = [
'hire_date'
];
If I cast the Hire Date or any other date field then it Throws an exception, as if the validation is not checking the format ; e.g 2017-08-AA
A two digit hour could not be found Data missing" on line 582 of
.....nesbot\carbon\src\Carbon\Carbon.php
If I remove the attribute casting for dates the validation works as expected and throws a validation exception. A workaround to keep the casting was to use mutators for all date fields
public function setHireDateAttribute ( $date )
{
$this->attributes['hire_date'] = TZ::isValidateDate($date) ? $date : null;
}
So my question is there something wrong with the setup ? if not what is the point of the date or date_format validations if I have to do it manually.

How to seed a date field in Laravel 5.3?

I've managed to set up a decent amount of seeding for data that needs to be in the database at launch. Everything was easy and working well until I needed to seed a DATE field with a default date.
I've tried the following...
DatabaseSeeder.php
class SettingsTableSeeder extends Seeder {
public function run()
{
Setting::create([
'name' => 'Start Date',
'date' => '2000-01-01'
]);
}
}
In my model I've been told adding this should fix it, but it didn't.
Setting.php
protected $dates = [
'created_at',
'updated_at',
'date'
];
Everytime I go to run the seeder it throws the error:
[InvalidArgumentException]
The separation symbol could not be found
Unexpected data found.
Trailing data
If I remove the quotes around the date it changes to..
[InvalidArgumentException]
The separation symbol could not be found
Data missing
Any idea how one goes about seeding a default value for a DATE database field?
If date is in the $dates array, insert Carbon instance instead of a string:
Setting::create([
'name' => 'Start Date',
'date' => Carbon::parse('2000-01-01')
]);
You'll need to make sure that Carbon is available to use at the top of the file:
use Carbon\Carbon;
It is auto-loaded by Laravel/Composer.
Just try inserting the date using Carbon like,
class SettingsTableSeeder extends Seeder {
public function run(){
Setting::create([
'name' => 'Start Date',
'date' => \Carbon\Carbon::createFromDate(2000,01,01)->toDateTimeString()
]);
}
}
The given answers by Alexey Mezenin and Jaymin Panchal both still resulted in the trailing data error being thrown.
What ended up working for me was including...
use Carbon\Carbon;
at the top of the DatabaseSeeder.php file.
Then changing my Setting::create to...
DB::table('settings')->insert([
'name' => 'Start Date',
'date' => Carbon::create('2000', '01', '01')
]);
for some reason I can't use Carbon with the standard Model::create method while seeding, but it works for DB::table('table')->insert.
$dates= [
['name' =>'Start Date'],
];
foreach ($dates as $date) {
Setting::create($date);
}

Yii2: Writing to database the date/time of the current record via expression

There is table with some columns. One of it date_of_record. Means the date when current row is inserted in database. In current version i just calculate this field in PHP code before save().
How it should be correctly done via expression? Example by opportunity
Use Timestamp Behaviors In Controller :
use yii\db\Expression;
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'date_of_record',
'value' => new Expression('NOW()'),
],
];
}
References
1) Timestamp Behaviors
2) Concept Behaviors

How to validate array of date that have to be inside two other date relative to a model in Laravel 51

I'm using boostrap-datepicker, with "multiple-date" option activated.
My dates looks like this: [date1, date2, ...].
I'm also using an hidden input to retrieve an "id". This "id" help me to retrieve "startdate" and "enddate" inside my model.
So I'm looking for a validation rule who can tell me if my dates are valid and if they are inside two other dates that correspond to the "id" of my model.
For now my id and dates rules are like this:
$rules = [
'id' => 'required|numeric|exists:event,id,isactive,1',
'dates' => 'array'
]
You can do this in very simple manner like this
Here is the documentation about writing rules for before and after
protected $rules = array(
'afterdate' => 'after:'.$yourDateForm,
'beforedate' => 'before:'.$yourDateTo
);
Note :
You shall also extend your date validation like this
'start_date' => 'required|date|after:tomorrow'
'finish_date' => 'required|date|after:start_date'
Update :
As the OP wants to get the date from db,
You shall do like this
$yourStartDate = Call to get Start Date from Table;
$yourEndDate = Call to get End Date from Table;
and the rule shall be
$validator = Validator::make(
array('date' => $yourStartDate),
array('date' => 'after:'.$yourEndDate)
);

Why is laravel's updateOrCreate creating new records instead of updating?

Code
Entry::updateOrCreate([
'intern_id'=>$intern['id'],
'created_at'=>Carbon::parse($input['date'])
],[
'company_id'=>$intern['supervisor']['company']['id'],
'content'=>$input['text']
]);
I'm using this code to try updating/creating a new record. It's suppose to matche intern_id and create_at column first. If found, then it creates a new one. However, it seems like it is always creating a new one and when it creates a new one, the company_id and intern_id column is set to 0 instead of the original value.
Note: intern_id or created_at are not PK columns.
Note2: created_at is a Date type, not DateTime
Use this code
Entry::updateOrCreate(['intern_id'=>$intern['id']],
[
'created_at'=>Carbon::parse($input['date']),
'company_id'=> $intern['supervisor']['company']['id'],
'content'=>$input['text']
]);
I believe this will work.
updateOrCreate() function of Model Abstract Class takes 2 parameters, but your parameter passing is breaking.
/**
* Create or update a record matching the attributes, and fill it with values.
*
* #param array $attributes
* #param array $values
* #return static
*/
public static function updateOrCreate(array $attributes, array $values = array())
{
$instance = static::firstOrNew($attributes);
$instance->fill($values)->save();
return $instance;
}
Entry::updateOrCreate(
[
'intern_id' => $intern['id'],
],
[
'created_at' => Carbon::parse($input['date'])
'company_id' => $intern['supervisor']['company']['id'],
'content' => $input['text']
]
);
because first argument array searched for first time
found one line with date and second line found other date deferent
-----------
// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
I had the same issue where it was only creating a record but it wasn't being updated in the event that the record exists.
The issue is that to allow for the mass assignment on the update you need to add the fields to be updated as fillable in your model.
In your Entry model you can have something close to this :
protected $fillable = [
'company_id',
'content',
];
I hope this helps in sorting out the issue.

Categories