How to deal with possible empty Input variable?

Laravel is pretty strict about any kind of errors – if you try to use undefined variable or don’t pass a necessary parameter you immediately see Whoops or another kind of error, depending how you handle them. There’s a little trick with Input variables that might save you some time and lines of code.

So, let’s assume the script is expecting a GET variable, something like [url]/[path]/?action=view – and we’re using \Input::get(‘action’) for that – what happens if action is not defined?

If your code looks like this:

$action = \Input::get('action');

You will see an error.

So we have to handle the possibility of empty action:

if (\Input::has('action')) { 
  $action = \Input::get('action'); 
  if ($action != '') { 
    // ... do some action
  }
}

There is another (easier readable?) way of doing it – with ternary IF:

$action = (\Input::has('action')) ? \Input::get('action') : '';
if ($action != '') { 
  // ... do some action
}

But the actually shorter way is to use a second parameter of \Input::get() function – a default value. If the parameter is undefined, Laravel will assign that second parameter and will not throw any errors:

if (\Input::get('action', '') != '') {
  // ... do some action
}

This way you can make that necessary check in one line/action instead of two. Of course, a more proper way of such validation might be a separate Validator usage, but for quick and simple Inputs this trick might, well, do the trick.

Like our articles?
Check out our Laravel online courses!

3 COMMENTS

    • Good point, Jokūbas. I’ve just seen a lot of those bigger IF-statements in people’s code. Your approach is as valid as mine, as long as it’s one IF-statement and not two sentences.

LEAVE A REPLY

Please enter your comment!
Please enter your name here