Skip to main content
Tutorial Free

How to deal with possible empty Input variable?

June 22, 2015
2 min read
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.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.