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.
As it’s written in a documentation (http://laravel.com/api/5.1/Illuminate/Support/Facades/Input.html#method_get), there’s no need to pass the second argument in Input::get method. Well, at least in this scenario. Default value is null, which makes it ok to use it like that: if (null !== \Input::get(“action”)) { … }
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.
array_filter( Input::except(‘_token’), ‘strlen’ );
in PHP is better check null or empty string with empty($var) : true/false
This also work : request()->filled(‘action’)