If you can't get the $dates mutator to work (https://laravel.com/docs/6.x/eloquent-mutators#date-mutators), I think this would be a good use case for manual mutators and accessors.
Essentially a mutator manipulates the value going in and an accessor manipulates the value coming out.
So
// mutator
public function setCreatedAtAttribute($date) {
$this->attributes['created_at'] = Carbon\Carbon::parse($date)->format('Ymd H:i:s');
}
// accessor
public function getCreatedAtAttribute($date) {
return Carbon\Carbon::parse($date)->format('Y-m-d H:i:s');
}
There's also date casting in some later versions of Laravel https://laravel.com/docs/6.x/eloquent-mutators#date-casting
floreasy liked this reply
Use carbon to format dates
In the model
Use Carbon\Carbon;
The format the retrieved dates
parth-kundariya, floreasy liked this reply
@parthkundariya Do you have supporting evidence that Carbon is deprecated in Laravel 6? It is still in the framework composer, it is installed on all of my new Laravel 6 projects and there hasn't been any notifications that it would be deprecated.
Just seeing if there is something I (and the community) missed.
Have you tried on your models
protected $dateFormat = 'Y-d-m H:i:s.v';
I used MSSQL on my last laravel project. Was using 5.8 tho. But that should work
floreasy liked this reply
Thanks for the answers.
My first problem was that my SQL Server user was configured in French ... Which means dates insertions in database HAVE TO be done in french ... but are recorded in datetimes in the database, that's how SQL Server works. I created a new user with default language "english" to get the "Y-m-d H:i:s" by default for me insertions. So now, wether for insertion or selection, the format is the same.
About the :
protected $dateFormat = 'Y-d-m H:i:s.v';
It works in "one way". The solution is indeed to use the mutators on the model , using setDateAttribute & getDateAttribute to return the required format for inserting and reading the datas.
Anyway, if someone faces the problem, the easiest is to set the correct language for the user ( not the server ) of sql server to get the generic datetime format.
Thanks again.
floreasy liked this reply
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community