Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 weeks ago.
0

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

Last updated 2 years ago.
1

Use carbon to format dates

In the model

    Use Carbon\Carbon;

The format the retrieved dates

2

Carbon is deprecated in Laravel 6

0

@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.

0

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

Last updated 2 years ago.
1

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.

1

Sign in to participate in this thread!

LoadForge

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

© 2022 Laravel.io - All rights reserved.