Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

'datetime' casted attribute returning current date from am empty string in the db #51500

Closed
NabilHassen opened this issue May 18, 2024 · 4 comments

Comments

@NabilHassen
Copy link

Laravel Version

11.5.0

PHP Version

8.3.4

Database Driver & Version

SQLite 3.19.1 for Windows 11

Description

When an empty string is persisted on a datetime column in the database and that column is casted by 'datetime' cast, you get current datetime instead of null as the output.

Steps To Reproduce

  1. create a migration which includes a datetime column as such:
    $table->dateTime('approved_at')->nullable();
  2. On the model class, cast the attribute using 'datetime' cast as such:
    protected function casts(): array { return [ 'approved_at' => 'datetime', ]; }
  3. Let us assume that we have a Post model and store some date as such:
    Post::create(['title' => 'Laravel', 'approved_at' => '']);
  4. And finally, let's try to access the 'approved_at' field as such:
    $post->approved_at;

Expected result: null or ''
Outcome: current datetime (i.e. same as now() method)

@Tofandel
Copy link
Contributor

Shouldn't it be Post::create(['title' => 'Laravel', 'approved_at' => null]); if your field is nullable

@NabilHassen
Copy link
Author

Shouldn't it be Post::create(['title' => 'Laravel', 'approved_at' => null]); if your field is nullable

@Tofandel

Using Livewire for example, if you set a date on the standard html datepicker and then clear it, then an empty string is passed instead of null.

I don't know what happens with just regular blade code, didn't try it.

@Tofandel
Copy link
Contributor

If you use the validator with nullable rule and retrieve the validated fields that should convert empty strings to null

@NabilHassen
Copy link
Author

Already did that, no difference.

@laravel laravel locked and limited conversation to collaborators May 20, 2024
@crynobone crynobone converted this issue into discussion #51507 May 20, 2024

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants