为什么带有 request->only() 的 if 语句不起作用?(拉拉维尔)

Sou*_*uri 5 php laravel

我的 if 语句有问题,但我不知道如何解决它。我想做的是,如果有人输入正确的 vCode,就会创建用户。如果 vCode 不正确,则不会创建用户,并且 $message 变量将为:vCode 无效。

但即使输入正确的 vCode,该消息仍然显示 vCode 无效。这是我的代码:

public function store(Request $request) {

    $vCode = $request->only('vcode');

    if ($vCode == 'stackoverflow') {
        // request only the form-inputs with the names: firstname, lastname and email.
        $oUser = User::create($request->only('firstname', 'lastname', 'email')); 
        $oUser->createPassword();
        $oUser->setRole(2);
        $oUser->save();
        $message = $oUser->getFullname().'succesfully created';
    } else {
        $message = "vCode valid";
    }

    return back()->with('successmessage', $message);
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*inz 11

$request->only('vcode')返回一个关联数组,其中只有一个元素。

如果您在通话中讨论了三件事only(),您的结果可能是:

$request->only('name', 'age', 'cheese');
// ['name' => 'Pingu', 'age' => '22', 'cheese' => 'gorgonzola']
Run Code Online (Sandbox Code Playgroud)

但如果你只有一个元素,你仍然会得到一个数组,只是它更小:

$request->only('vcode');
// ['vcode' => 'stackoverflow']
Run Code Online (Sandbox Code Playgroud)

所以你需要改变你的if条件:

if ($vCode['vcode'] == 'stackoverflow') {
    // should work
}
Run Code Online (Sandbox Code Playgroud)

或者您可以将其作为单个值获取:

$vCode = $request->input('vcode');
if ($vCode == 'stackoverflow') {
    // should work
}
Run Code Online (Sandbox Code Playgroud)