【问题标题】:Laravel - Constant expression contains invalid operations in x:\project\app\Model.phpLaravel - 常量表达式包含 x:\project\app\Model.php 中的无效操作
【发布时间】:2017-10-19 09:18:30
【问题描述】:

我正在尝试使用 laravel 验证一些数据,我已经在模型本身中实现了这些数据,例如:

类集合扩展模型 { 受保护的 $guarded = [ 'id' ];

public $allowedDataTypes = [

'Date',
'Text',
'Number',
'Email',
'Checkbox',
'Image',
'File',

];





25    public static $rules =  array([
26
27  'fields.*.fieldName' =>  
28      [       
29          'unique' => 'Please ensure that the fields are uniquely named.',
30          'required' => 'You must specify a name for your fields.'
31      ],
32
33  'fields.*.dataType' =>
34      [
35          'required', 'You must specify a data type for your fields.',
36          'in:'.implode(',', $allowedDataTypes)
37      ]
38
39  ]);

但是,在提交数据并假设它通过此验证时,它给了我标题中看到的错误:

常量表达式在 {link to 型号}:39

我也对代码行进行了编号,但我不确定为什么会发生这种情况。

提前感谢您的任何指导。

【问题讨论】:

  • dd($allowedDataTypes); 做什么输出? (在函数开始时执行)
  • 它甚至不会让我走那么远。我将在问题中添加它的声明
  • php !=java。它只是不会编译,......还没有。你不能在类属性上创建像这样的嵌套数组。相反,将它们设置在构造函数上。
  • 您不能在声明中使用表达式。 implode(',', $allowedDataTypes)正在触发错误

标签: php laravel validation


【解决方案1】:

不能在类变量声明中使用 implode 函数。这是因为类变量是在运行时之前启动的。

如果你想使用内爆函数,你可以使用函数或使用构造函数。

例如:

public function rules()
{
    return [
        'fields.*.fieldName' => [
            'unique' => 'Please ensure that the fields are uniquely named.',
            'required' => 'You must specify a name for your fields.'
        ],

        'fields.*.dataType' =>      [
            'required', 'You must specify a data type for your fields.',
            'in:'.implode(',', $this->allowedDataTypes)
        ]

    ];
}

【讨论】:

  • 我将如何使用它呢?验证器中的 $this->rules()?
  • 我将编辑我的答案,以便如果您在上面显示的模型中使用验证器,则可以使用$this->rules()
  • 尝试将其设为public static $allowedDataTypes 并将$this->allowedDataTypes 更改为self::$allowedDataTypes
  • 好的。伙计,我希望你今天能找到一张 50 英镑的钞票之类的东西。谢谢!
猜你喜欢
  • 2018-12-02
  • 2021-03-07
  • 2017-04-11
  • 2017-06-18
  • 1970-01-01
  • 2017-05-16
相关资源
最近更新 更多