添加与表单无关的验证

Add a validation which is not related to the form

我想在表单上添加验证。我的实际表格有效,这里是:

public function store(Request $request, $id)
{
    $this->validate($request, [
        'subject' => 'required',
        'body' => 'required',
    ]);

    // Do something if everything is OK.
}

现在,我想检查用户是否也是 "active"。所以像:

\Auth::user()->isActive();

并且 return 一个错误 与其他验证错误 如果用户不活跃。

我可以向验证器附加一些与表单本身无关的东西吗?我的意思是如果用户不活跃,我想在其他错误中添加一个错误。

该代码仅验证请求变量(validate() 函数的第一个参数)。所以你必须在请求中加入一些东西来验证它。它将规则应用于给定的 object/array。

$request->is_active = Auth::user()->isActive();
$this->validate($request, [
    'subject' => 'required',
    'body' => 'required',
    'is_active' => true //or whatever rule you want
]);

无论如何,我从未尝试过,所以不确定它是否有效。通常的方法是做一个 if

if ( !Auth::user()->isActive() ) {
    return redirect->back()->withErrors(['account' => 'Your account is not active, please activate it']);
}

//continue here