模型中的Laravel日期验证

时间:2018-11-18 18:37:34

标签: php laravel laravel-4 eloquent

我正在尝试不允许用户在特定日期保存数据。现在,即使用户选择了特定日期,我的代码也会导致用户无法保存数据。日期不在特定日期时,如何允许用户保存数据?

代码:

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();
    });

3 个答案:

答案 0 :(得分:0)

带有unix时间戳的快速向导。

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

            //Disable save function between specific
            if ( !(property_exists($model, 'always_writable') 
                && $model->always_writable) 
                && (time() >= $form && time() <=$to)){
                $model->setErrors(trans('validation.read_only'));
                return false;
            }
            return $model->validate();
        });

edit:添加了always_writable条件。 edit2:使您的always_writable检查实际上是明智的。

答案 1 :(得分:0)

您需要检查查询的数量:

//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();
    });

答案 2 :(得分:0)

不太确定要在查询中实现什么意思

brew tap homebrew/cask-versions

这基本上使系统中的所有用户的日期列在$ from和$ to之间。大概这将永远是正确的。那不应该是:

User::whereBetween('date', [$from, $to])->get()

这意味着:当前登录用户的日期列在$ from和$ to之间?

替代:

Auth::user()->whereBetween('date', [$from, $to])->count()