Wrong date fetch with eloquentt from MongoDB - laravel

I get wrong date from MongoDB using Eloquent in Laravel. My record in database looks like this
"created_at" : ISODate("2020-11-17T15:30:42.131+01:00")
Code to get records from MongoDB
$taskObj = TaskComments::where('task_id', $task_id)->get()->toArray();
Result date for created_at is
1970-01-25 20:31:23 which is wrong, I would like to get in this format 2020-11-17 15:30:42
I would like to create correct Mutator or to define a default date format in Laravel or in MongoDb I am not sure.
Any help is appreciated.

This is fixed my problem, I used a mutator in Model of TaskComments
public $timestamps = FALSE;
public function getCreatedAtAttribute($created_at){
return $created_at->toDateTime()->format('Y-m-d H:i:s');
}

Related

Wrong timezone with Eloquent Model timestamps on $model->get(), but correct with print_r()

I am experiencing something quite weird for any Eloquent Model with Laravel 7!
P.S.: I've run on every test I did:
php artisan optimize:clear
I don't know what I am missing here!
I won't post any code because that's a simple CRUD with Model Bindings.
When saving the created_at and updated_at fields, it is correctly saved in the MySQL with my timezome "America/Sao_Paulo".
But if I do this in any controler:
return $model->get()
or
return $model->paginate()
or
Model::all()
I get the response:
{
"data": [
{
... other fields
"created_at": "2020-08-23T15:22:41.000000Z",
"updated_at": "2020-08-23T15:22:41.000000Z"
}
]
}
And it returns the wrong time with +1 hour.
However, here is where things get weird... if I print_r() any of them, I get the corret time!
Array
(
... other fields
[created_at] => 2020-08-23 12:22:41
[updated_at] => 2020-08-23 12:22:41
)
I tried to use:
public function getDateFormat()
{
return 'Y-m-d H:i:s';
}
But no effect!
Thanks in Advance!
Laravel 7 uses a new date serialization format when using the toArray or toJson method on Eloquent models with UTC
Before Laravel 7, dates would be serialized to a format like the following :
2019-12-02 20:01:00
Dates serialized using the ISO-8601 format will appear like :
2019-12-02T20:01:00.283041Z
Please note that ISO-8601 dates are always expressed in UTC.
If you would like to keep using the previous behavior you can override the serializeDate() method on your model :
use DateTimeInterface;
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
See the official upgrade doc here
If you have changed the timezone config in config/app.php but saving the date in the database with other timezone formats then keep the timezone to UTC so laravel doesn't change it to other formats when calling it from model class, or you can do the opposite by saving it by UTC format in database then change the config to a timezone that your app needs.
// config/app.php
'timezone' => 'UTC',

Time format of database field, help needed

Time is stored in my database as H:i:s format for a timefield.
When I query I want time returned as hours:minutes without the seconds part.
I tried to set the "protected $dateFormat " setting using a Mutator. Can anyone show an example of the dateFormat setting needed? The database must remain hour:minute:seconds time settings, only the retrieved value needs to be changed for display.
protected $dateFormat = 'Y-m-d H:i:s'; // ?
One way to solve it is to treat dates as Carbon instances. The format to save on database will be auto-converted and you should use in any format.
protected $dates = [
'field_name'
];
https://laravel.com/docs/5.8/eloquent-mutators#date-mutators
// converting db column name time_match into the function as getTimeMatchAttribute worked for me.
public function getTimeMatchAttribute($value){
return date('H:i',strtotime($value));
}
you can make it with getters function in your model
like this:
public function getTimeAttribute($time){
return date('h:i',strtotime($time))
}
Time in function name should be your column name in upper case

Laravel sqlsrv - unable to create timestamps()

I am migrating an existing projekt in L5.1.x to a new server running with Server 2012 and an SQL Server 2012.
I have some problems when using the timestamps() fields for tables. When ill add in my Scheme:
$table->timestamps();
Ill get the created_at and updated_at column with type "datetime".
But with that new configuration when ill try to add a Model to this database i am always getting that error:
QueryException: Unable to convert an nvarchar Value to and datetime Value ....
When ill disable the timestamp fields in my Model, everything is working:
public $timestamps = false;
.. but of course no values for created_at and updated_at
I dont know what cause this problem - any ideas? i could manually set the created_at and updated_at field to "GETDATE()" - but i would like to use Laravels base functionality.
Ok ill found the problem - Laravel creates a datetime with format of:
"Y-m-d H:i:s.u"
But the SQL Server wants the format of:
"Y-d-m H:i:s"
So when you update your model function with:
public function fromDateTime($value)
{
return Carbon::parse(parent::fromDateTime($value))->format('Y-d-m H:i:s');
}
You are able to convert to date format to the correct value for your SQL Server ( dont know why its Y-d-m, its not my server ;) )

L5 Unable to store Jquery datepicker value to database

I am using L5 with eloquent. In my model i defined below function for necessary database table field.
public function getBuyingDateAttribute($value)
{
return Carbon::parse($value)->format('d/m/Y');
}
Datepicker
$( "#buying-date" ).datepicker({dateFormat: 'dd-mm-yy'});
I am able to display a current value with this format in my form(usingform model binding) but when i try to store or update the field the value comes null. I am a newbie with Laravel and Eloquent. How can i format and store the data properly ? Anyhelp would be appreciated.
if in your form the date column name is date then use the following in your controller
$date = date('d/m/Y',strtotime($request->date));
//here $request is the object of Request class

Convert timestamp to date in Laravel?

How can I return from the database all rows with a timestamp converted to a date (d-m-Y H:i), using the all() method?
It's not created_at or updated_at column, it's custom attribute, call it birthday if you wish.
timestamp columns like created_at are being parsed first. the U is simply the timestamp format. you can return your own format. for other formats see date docs.
edit: as stated in my comment, getDateFormat() is for both ways (insert, selects). your best bet would be using format inside the model. example:
public function getMyBirthdayAttribute()
{
return $this->my_birthday->format('d.m.Y');
}
use $model->my_birthday to call the attribute.
// controller
$posts = Post::all();
// within sometemplate.blade.php
#foreach($posts as $post)
my formatted date: {{ $post->my_birthday }}
#endforeach
The better way to manage dates with Laravel IMHO is to use the getDates accessor that is build into Laravel.
All you need to do is to set a method on your Model as such.
public function getDates()
{
return [
'my_birthday',
'created_at',
'updated_at',
];
}
This will return a Carbon object. Carbon is insanely awesome for manipulating dates.
It is what Laravel does by default to created_at and updated_at.
You can then do things like:
$my_birthday->diffForHumans() // 2 Days ago
$my_birthday->format('d.m.Y') // 20.02.1979
There are tons of helpers here for you. Check out the Carbon docs: https://github.com/briannesbitt/Carbon
Definitely worth learning. It might not be easy to understand for a beginner. However, I would advise you take a look and get your head around it. It will change your life - Dates can be a pain!
In this case, you need to convert the date within the query, if mysql is being used as your database then you may use a raw query like this:
// Assumed my_birthday is like 1255033470
$raw = DB::raw("date_format(from_unixtime(my_birthday),'%b %d, %Y %l:%i %p') as dob");
$result = Model::get(array('id', 'username', $raw));
You may write it within single line:
$result = Model::get(array('id', 'username', DB::raw("...")));
Just place this on your code
$post it depend on what you create
$post ->created_at->format('d.m.Y')

Resources