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.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by