Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

davidebo's avatar

input datetime-local value updating

Hello, i'm trying to NOT update the input datetime-local value when i submit my form. But everytime i send form, i always see post->published_at value updated with current date , even if published_at input is not touched

Post.php

protected $dates = ['published_at']; 
protected $casts = [
    'published_at' => 'datetime',

];

PostController.php

$inputPublishedAt = $req->input('published_at'); 
if (!empty($inputPublishedAt)) { 
$newPublishedAt = Carbon::parse($inputPublishedAt)->setTimezone($post->published_at->timezone);
       if (!$post->published_at->startOfHour()->eq($newPublishedAt->startOfHour())) {
            $post->published_at = $newPublishedAt;
        } else {
		// not change $post->published_at
        }
    }

value on database: 2024-12-14 14:03:20

what i'm trying to do is to not update the value if the request->published_at and $post->published_at are different for a maximum of one hour , anyone can help ? thank you

1 like
6 replies
vincent15000's avatar

You necessarily have a place in your code where you update this property.

Can you show the entire update() function in your controller ?

davidebo's avatar

@vincent15000 Unfortunately is the only point where i have published_at updated, maybe datetime-local input is always updated when submitting form ?

Shivamyadav's avatar

I think 🤔 this would works . According to the question

$inputPublishedAt = $req->input('published_at');

if (!empty($inputPublishedAt)) {
    $newPublishedAt = Carbon::parse($inputPublishedAt)->setTimezone($post->published_at->timezone);

    // Check if the difference is more than one hour
    if ($post->published_at->diffInHours($newPublishedAt, false) > 1) {
        $post->published_at = $newPublishedAt;
    } 
    // Else, do nothing and keep the original value
}
Shivamyadav's avatar

@davidebo first remove any one of your cast property from Post model the both are used for achieving the same data types

use Carbon\Carbon;

$inputPublishedAt = $req->input('published_at');

if (!empty($inputPublishedAt)) {
    $newPublishedAt = Carbon::parse($inputPublishedAt);

    // Ensure `$post->published_at` is not null before comparing
    if ($post->published_at) {
        // Compare hours difference
        if ($post->published_at->diffInHours($newPublishedAt, false) > 1) {
            $post->published_at = $newPublishedAt;
        }
    } else {
        // If `published_at` is null, set the new value
        $post->published_at = $newPublishedAt;
    }
}

// Save the post if updated
$post->save();

I hope this will works

1 like
davidebo's avatar

@Shivamyadav thank you, I solved it, in database i had 'on update CURRENT_TIMESTAMP' i didn't know that.

1 like

Please or to participate in this conversation.