casts datetime format in Laravel - php

As the Laravel document, we can cast the value to DateTime.
https://laravel.com/docs/5.8/eloquent-serialization#date-serialization
protected $casts = [
'birthday' => 'date:Y-m-d',
'joined_at' => 'datetime:Y-m-d H:00',
];
There result is :
"2020-05-29 00:00:00"
but i want to result like that:
"2020-10-29T00:00"
I can use Carbon with format "Y-m-d\TH:i");
if possible to format like "2020-10-29T00:00" if I don't use the Carbon?
any ideas will be appreciated.

As the Carbon documentation (https://carbon.nesbot.com/docs/#api-formatting) states. You can use format() function.
$dt->format("Y-m-d\TH:i")

Related

Yii2 GridView convert date format from mm/dd/yyyy

I am trying to convert a date from yyyy-mm-dd to mm-dd-yyyy Yii2 GridView; however I don't know how the date function requires a timestamp, and I can't get a timestamp from this string.
[
'attribute' => 'created_at',
'format' => ['datetime', 'php:m/d/Y H:i:s']
],

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

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'
];

Laravel 8 with Backpack - datetime formatting on the frontend?

I am currently trying to format a datetime object that I access like this:
Blade:
{{ $event->start }} and {{ $event->end}}
this outputs something like this on the frontend blades:
2021-12-02 22:30:00 ($event->start) 2021-2021-12-02 23:00:00 ($event->end)
the formatting above is also how it is stored as a DATETIME object in the database.
Because I use other elements, like a fullcalendar, I dont want to change the way the database stores the dates, just formatting the dates on the frontend/controller directly.
Controller:
if ($course == 'course') {
$view = 'pages.course.current_course';
$id = '8';
}
// get the course data from the database
$events = DB::table('eventaries')
// map the current view $id to the database query
->where('category', $id)
// check if event is expired
->where('start', '>', now())
->get();
// pass through the data to the correct views
return view($view, [
"events" => $events
]);
But I need the following formatting: Sunday. 12th December 2021, 22:30 ($event->start) and 23:00 ($event->end)
I already got the formatting in the BackPack Backend right by adding 'format' => to the CrudController, like this:
CrudController:
CRUD::addColumn([
'name' => 'start',
'label' => 'Start',
'type' => 'datetime',
'format' => 'DD.MM.Y - H:mm',
]);
CRUD::addColumn([
'name' => 'end',
'label' => 'End',
'type' => 'datetime',
'format' => 'DD.MM.Y - H:mm',
]);
If you have Model defined for that particular table. you can define accessor for those two column, like
public function getStartAttribute($value)
{
return Carbon::parse($value)->toDayDateTimeString();
}
It will return output something like Mon, Nov 29, 2021 05:45 PM
Define these type of function for end column.
Refer this Carbon Document for other format and date operation
If you don't have Model you can use Carbon class in blade or controller directly
We will use createFromFormat() and format(), createFromFormat() will take two argument first give format of date and second one date and format() take one argument give formate as you want. you can see bellow examples:
Example 1:
$post->created_at->format('d-m-Y');
Example 2:
\Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d-m-Y')

Laravel date_format Validation Fails on Textual Month

My JavaScript library datepicker returns dates in a format "March 2019."
Carbon can decode it.
$date = Carbon::createFromFormat('M Y', $request->month);
Laravel fails on date_format validation.
$request->validate([
'month' => [
'required',
'date_format:M Y',
],
]);
saying
The month does not match the format M Y.
I have tried all PHP date formats from here
: M, MM, mm, m.
$request->validate([
'month' => [
'required',
'date_format:F Y',
],
]);
You're using the wrong format. You need to use standard PHP formats, which is what Carbon and Laravel's validation uses. You can find them in the PHP Docs for date()
So change your rule to:
date_format:"F Y"

Laravel 5 How to submit dates to SQL database

I've been stuck for days, I can't get my dates to save to my database and having issue after issue. Can someone recommend a video/article or just plain explain on how to fully deal with dates?
Migration
$table->dateTime('start_date');
$table->dateTime('end_date');
Controller
public function store(Request $request)
{
$this->validate(request(), [
'name' => 'required',
'description' => 'required',
'status' => 'required',
'startdate' => 'required',
'enddate' => 'required'
]);
Event::create(request(['name', 'description', 'status', 'start_date', 'end_date']));
return redirect('/events');
}
Model
THIS IS OBVIOUSLY THE ISSUE and I would paste things but theres multiple things I've put here and nothing works.
This is the dd of the request
+request: ParameterBag {#40 ▼
#parameters: array:6 [▼
"_token" => "yjU5A0Z5dpRES7KWK82fRMbHMRQkaooe27vYKlo7"
"name" => "My first event"
"status" => "Inquery"
"description" => "this is my desc"
"start_date" => "02/16/2017 6:36 PM"
"end_date" => "02/24/2017 6:37 PM"
]
You need to provide the dates to the database (via laravel) in a format that it understands.
You're using the d/m/Y H:i A format on the front end (see the PHP Date page for more on date formats). The database likes to receive dates in the format Y-m-d H:i:s. Even better, laravel can insert Carbon date objects into the database with no formatting on your part.
As Carbon comes with Laravel, you can use it to change your date string into a Carbon object.
$start_date = \Carbon\Carbon::createFromFormat('d/m/Y H:i A', $request->input('start_date'));
As you can see, Carbon takes the date string and as the format has been supplied, it's easy for it to create a new Carbon object. This can be directly inserted into the database.
If you really wanted, you could explicitly cast it into a string with $start_date->toDateTimeFormat();, or even $start_date->format('Y-m-d H:i:s');.
// put the first three elements in the insertData array
$insertData = request()->only(['name', 'description', 'status']);
$insertData['start_date'] = \Carbon\Carbon::createFromFormat('d/m/Y H:i A', $request->input('start_date'));
$insertData['end_date'] = \Carbon\Carbon::createFromFormat('d/m/Y H:i A', $request->input('end_date'));
// both dates are now carbon objects, not strings
Event::create($insertData);

Categories