Stackingcoder Stackingcoder - 3 months ago 3x
PHP Question

Why does if statement with request->only() not work ? (Laravel)

i have a problem with a if statement and i don't
know how to fix it. What i want to do is if someone puts in the correct
vCode, the user will be created. If the vCode is incorrect the user will not be created and the $message variable will be: vCode invalid.

But even when put in a correct vCode the message still says vCode invalid.
Here is my code:

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'));
$message = $oUser->getFullname().'succesfully created';
} else {
$message = "vCode valid";

return back()->with('successmessage', $message);


$request->only('vcode') returns an associative array with only one element in it.

If you'd had three things in the only() call, your results might have been:

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

But if you have only one element, you still get an array, it just happens to be smaller:

// ['vcode' => 'stackoverflow']

So you need to change your if condition:

if ($vCode['vcode'] == 'stackoverflow') {
    // should work

Or you could just get it as a single value:

$vCode = $request->input('vcode');
if ($vCode == 'stackoverflow') {
    // should work