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

naykel's avatar

Livewire date casting and validation problem

I am trying to implement date validation on a livewire component, and it appears that date casting happens before validation resulting with errors.

After days of googling, I have tried so many things I am at a loss, but from what I have figured out this is only a problem when using nested properties.The common pattern I have found is:

In the model

protected $casts = [
    'expires_at' => 'date',
];

protected $appends = ['expiry_date_for_editing'];

public function getExpiryDateForEditingAttribute()
{
    return $this->expires_at->format('d/m/y');
}

public function setExpiryDateForEditingAttribute($value)
{
    dd('why is firing before validation takes place?????');
    $this->expires_at = Carbon::createFromFormat('d/m/y', $value)->format('Y-m-d');
}

In the livewire component validation rules I have

protected $rules = [
    'editing.expiry_date_for_editing' => 'required',
];

I am aware that there is no date formatting in the validation rules above but I can't even get the required rule to fire. To test I deleted the date and tried to save save it just throws and error saying data missing.

0 likes
4 replies
naykel's avatar

I tried working with the rules as you have linked to but I think the problem exists because the mutator is firing before the validator so it does not get the chance to do it's job.

In the example I have above you will see that the only validation I have is required so you would expect a validation error when you submit an empty field but this is not the case, the error thrown is a carbon error.

Hope this makes it a little cleared.

limeframe's avatar

@naykel hi! Its a year old post but..... did you find a solution? I have exact the same problem. Mutator fired before the rules check Thanks

naykel's avatar

@limeframe from memory I did not find a solution to this exact problem. I ended up created a date cast with the expectation that the date picker will always supply the correct format. I am sure future me will not like this but as it was only a small scale app and I was fed up trying to solve the problem so I just threw a band aid on.

// livewire validation
protected $rules = [
    'editing.expired_at' => 'sometimes|date',
];

// custom cast
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class DateCast implements CastsAttributes  {
    
        public function get($model, $key, $value, $attributes)
        {
            return $value ? Carbon::createFromFormat('Y-m-d H:i:s', $value)->format('d-m-Y') : null;
        }

        public function set($model, $key, $value, $attributes)
        {
            return $value ? Carbon::parse($value) : null;
        }
    }
}

Please or to participate in this conversation.