Laravel 8 with Backpack - datetime formatting on the frontend? - php

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

Related

Yii2: display dates in user time zone

In my DB I store all datetime fields in UTC format. Also, I have the ability to change default time zone by users. Each user can have own time zone, different from UTC.
How shall I display all model datetime fields in this case?
I have an idea. To do this action for each ActiveRecord model:
public function init()
{
parent::init();
$this->on(ActiveRecord::EVENT_AFTER_FIND, function($event) {
$this->created_date = (new \DateTime('now', new \DateTimeZone("Europe/Kiev")))->format("Y-m-d H:i:s");
});
}
But I'm not sure it's the best way for big amount of models...
if the dates are stored in UTC why not append the string UTC along the time and display it
$time = strtotime($this->created_at.' UTC');
date("Y-m-d H:i:s", $time);
Your code will look like this
public function init()
{
parent::init();
$this->on(ActiveRecord::EVENT_AFTER_FIND, function($event) {
$time = strtotime($model->create_at.' UTC');
$this->created_date = date("Y-m-d H:i:s", $time);
});
}
if I would do it I would just create a separate Helper and use it to display the date in the local format rather than EVENT_AFTER_FIND
Another alternative is to use this Extension
Search for frontend/config/main.php
Try putting in
return [
...
'components' => [
...
a FORMATTER part like
'formatter' => [
'dateFormat' => 'dd/MM/yyyy',
'datetimeFormat' => 'dd/MM/yyyy H:i:s',
'timeFormat' => 'H:i:s',
'locale' => 'it-IT',
'decimalSeparator' => ',',
'thousandSeparator' => '.',
'currencyCode' => 'EUR',
'numberFormatterSymbols' => [
NumberFormatter::CURRENCY_SYMBOL => '€',
],
'timeZone' => 'Europe/Rome',
],
Set your parameters like TimeZone, Currency, etc...
NB: I dont remember but maybe the NumberFormatter part need some other setup so delete the numberFormatterSymbols part if it give to you an error

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

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

How to validate an input date from individual day, month, year input in Laravel 5

I have a user registration form which takes input birth day split in 3 different input fields i.e. day, month, year
{!! Form::selectMonth('month', null) !!}
{!! Form::selectRange('day', 1, 31, null) !!}
{!! Form::selectYear('year', Carbon\Carbon::now()->year, (new Carbon\Carbon('100 years ago'))->year, null) !!}
In the backend I have modified the Registrar.php/validator() to check the input date is a valid one:
public function validator(array $data) {
$data['date_of_birth'] = Carbon::create($data['year'], $data['month'], $data['day'], 0, 0, 0)->toDateString();
$current_year = Carbon::now()->year;
$hundred_years_ago = (new Carbon("100 years ago"))->year;
return Validator::make($data, [
'year' => 'Required|Integer|Between:'.$hundred_years_ago.','.$current_year,
'month' => 'Required|Integer|Between:1,12',
'day' => 'Required|Integer|Between:1,31',
'date_of_birth' => 'Required|Date',
]);
}
But surely it doesn't check if an invalid date was provided. If the user provides an invalid date such as 31st February, 1982, the Carbon::create() transforms the date to 3rd March, 1982 which turns out to be a valid one.
If I want to filter this type of date input what do I need to do? I do believe this is likely a very common requirement for those who don't use any datepicker of some sort.
Laravel using the strtotime and checkdate functions to validate a date.
How the validateDate function of Laravel works? An example:
strtotime('30-2-2015'); // returns a timestamp
checkdate(2, 30, 2015); // returns false
// laravel raises an error
Therefore, the value of $data['date_of_birth'] should be a string in a particular format.
public function validator(array $data)
{
$data['date_of_birth'] = $data['day'].'-'.$data['month'].'-'.$data['year'];
$current_year = Carbon::now()->year;
$hundred_years_ago = (new Carbon("100 years ago"))->year;
return Validator::make($data, [
'year' => 'Required|Integer|Between:'.$hundred_years_ago.','.$current_year,
'date_of_birth' => 'Required|Date',
]);
}
Also you can ignore the validation of day and month, since the date will be validated.

Created date getting set to 0000-00-00 00:00:00 with the CTimestampBehavior in yii while updating

I have attached time stamp behavior to my Model as:
public function behaviors()
{
return array(
'CTimestampBehavior' => array(
'class' => 'zii.behaviors.CTimestampBehavior',
'createAttribute' => 'created_date',
'updateAttribute' => 'modified_date',
'setUpdateOnCreate' => true,
),
);
}
It is setting the created and modified date correct while creating the record. While updating it updates the modified date correctly but sets the created date to 0000-00-00 00:00:00. Is there any thing wrong in this code?
I'm using the $Model->update() function for updating the record.
Found the solution. Found that the date format for created data was incorrect and therefore was not getting stored in the database. Changed the created date into the correct format before updating the model and its working.
$model->created_date=date("Y-m-d H:i", strtotime($model->created_date));
$model->update();

Categories