Laravel blank and filled helper The hand blank and filled helpers for Laravel are a nice way to determine variable state https://laravel.com/docs/master/helpers#method-blank
requires: laravel 5.5

In this refactor we show you the power of the blank() and filled() helpers. In this way you can easily determine whether a variable if filled, thus has a value.

Original code


        $null            null;
        
$string          "string";
        
$array           = ['a''b''c'];
        
$collection      collect($array);
        
$emptyArray      = [];
        
$number          1;
        
$emptyCollection collect([]);
        
$boolean         false;
        
$allVars         get_defined_vars();

        
$blanks $filled $empty = [];
        foreach (
$allVars as $key => $var) {
            if (!isset(
$var) || (is_countable($var) && count($var) === 0)) {
                
array_push($blanks$key);
            } else {
                
array_push($filled$key);
            }
            if (empty(
$var)) {
                
array_push($empty$key);
            }
        }

        
$output "Blanks : " implode(', '$blanks) . "<br />";
        
$output .= "Filled : " implode(', '$filled) . "<br />";
        
$output .= "Empty : " implode(', '$empty);

        

Refactored code



        $null            null;
        
$string          "string";
        
$array           = ['a''b''c'];
        
$collection      collect($array);
        
$emptyArray      = [];
        
$number          1;
        
$emptyCollection collect([]);
        
$boolean         false;
        
$allVars         get_defined_vars();

        
/**
         * blank() and filled() are two Laravel helpers
         */
        
$blanks collect($allVars)->filter('blank');
        
$filled collect($allVars)->filter('filled');
        
$empty  collect($allVars)->filter(fn($var) => empty($var));

        
$outputRefactored "Blanks : " $blanks->keys()->join(', ') . "<br />";
        
$outputRefactored .= "Filled : " $filled->keys()->join(',') . "<br />";
        
$outputRefactored .= "Empty : " $empty->keys()->join(',');

        

Here is the output of the code

This is the output of original

Blanks : args, null, emptyArray, emptyCollection
Filled : string, array, collection, number, boolean
Empty : args, null, emptyArray, boolean

This is the output of refactor

Blanks : args, null, emptyArray, emptyCollection
Filled : string,array,collection,number,boolean
Empty : args,null,emptyArray,boolean

Want to learn more from LLoadout ?

LLoadout is your loadout for Laravel, helping you kickstart your development process. Besides this refactoring site we also make some cool packages and video tutorials !

Go to LLoadout on github