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

DilipkumarC's avatar

How to validate date in laravel model

I'm trying to not allow the user to save data on a specific date. Now my code will lead to user can't save data even if the user selected a specific date. How do I allow the user to save data when the date is not on the specific date?

Code :

static::save(function($model)
    {
        //User can't save data between this date
        $from = date('2018-01-01');
        $to = date('2018-11-19');

        //Disable save function between specific
        if (User::whereBetween('date', [$from, $to])->get()&&
           (!property_exists($model, 'always_writable') || !$model->always_writable)) {
            $model->setErrors(trans('validation.read_only'));
            return false;
        }
        return $model->validate();
    });
0 likes
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@dilipkumarc

You need to check against the count of the query. Try this-

//if count is greater than 0

static::save(function($model)
    {
        //User can't save data between this date
        $from = date('2018-01-01');
        $to = date('2018-11-19');

        //Disable save function between specific
        if (count(User::whereBetween('date', [$from, $to])->get()) > 0 &&
           (!property_exists($model, 'always_writable') || !$model->always_writable)) {
            $model->setErrors(trans('validation.read_only'));
            return false;
        }
        return $model->validate();
    });
6 likes

Please or to participate in this conversation.