Laravel 5 How to submit dates to SQL database - php

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);

Related

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')

How Yii2 GridView date format works

. Good day! Please tell me a technical question, in GridView Yii2, code:
['attribute' => 'request_date_create',
'value' => function ($model) {
return Yii::$app->formatter->asDateTime($model->request_date_create, 'php: d.m.Y H:i:s');
},
],
Does it display the date 3 hours later than the one taken from the database? And this code displays normal :
['attribute' => 'request_date_create',
'value' => function ($model) {
return Yii::$app->formatter->asDateTime(strtotime($model->request_date_create), 'php: d.m.Y H:i:s');
},
],
And this code generally displays nonsense :
[
'attribute' => 'request_date_create',
'format' => ['date', 'php: d.m.Y H:i:s']
],
Why? There is some nuance, but I cannot understand what
[
'attribute' => 'request_date_create',
'format' => ['datetime', 'php:d.m.Y H:i:s']
],
Try to use datetime format and remove whitespace after php:
Looks like PHP time zone is different. See docs https://www.yiiframework.com/doc/api/2.0/yii-i18n-formatter#$defaultTimeZone-detail and example https://www.yiiframework.com/wiki/684/save-and-display-datetime-fields-in-different-formats-in-yii2#tip-3-controlling-global-formats how to set formater time zone, date and time formats

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"

Yii2 kartik-datecontrol timepicker Update

I am using a DateControl widget by Kartik in my Yii2-powered system. The widget correctly saves the time I've selected. However, when I tried to update the data, it just always shows "12:30" as the time and not the time from the database. I am still new to Yii2 and I there's not much information on the Internet regarding this issue. Thank you for the help!
Code for my form:
<?= $form->field($model, 'class_start_time')->widget(DateControl::classname(), [
'type'=>DateControl::FORMAT_TIME,
])
?>
<?= $form->field($model, 'class_end_time')->widget(DateControl::classname(), [
'type'=>DateControl::FORMAT_TIME,
])
?>
Code for the config:
'displaySettings' => [
Module::FORMAT_DATE => 'dd-MM-yyyy',
Module::FORMAT_TIME => 'HH:mm a',
Module::FORMAT_DATETIME => 'dd-MM-yyyy HH:mm:ss a',
],
// format settings for saving each date attribute (PHP format example)
'saveSettings' => [
Module::FORMAT_DATE => 'php:U', // saves as unix timestamp
Module::FORMAT_TIME => 'php:H:i:s',
Module::FORMAT_DATETIME => 'php:Y-m-d H:i:s',
],
I found the solution. The displaySettings should be hh:mm a and not HH:mm a. There is a mismatch in the format which causes the display to be in error when the time is in PM (or greater than 12:00:00).

How to change the data type (datetime) to (date) in the conditions of a running find?

I need get all posts from the current day (today), with the find below I'm not getting anything because the field pub_date (datetime) has time and the new \Datetime() returns the current date and time so, the date will match but the time not.
$posts = $this->find('all', [
'fields' => [
'Posts.id',
'Posts.title',
'Posts.body',
'Posts.pub_date',
],
'conditions' => [
'Posts.is_active' => true,
'Posts.pub_date' => new \Datetime()
],
]);
In short terms, I need get all posts with date equal "today" dont matter the time.

Categories