Check if Laravel object has items

Viewed 1047

I have to ensure that I only display a foreach loop in blade - only if there are elements in my variable.

So I need to check if my variable is - null or not (there could be no such variable in a very dynamic blade) - it has elements - if it is array, if it is collection, if it is a paginated collection?

So far I made this little function but it looks kinda odd and as I am not very good with Laravel I am wondering if there is already something better?

public static function hasItems($object) {
        if (is_null($object)) {
            return false;
        }

        //array
        if (
            is_array($object) && 
            count($object) > 0
        ) {
            return true;
        }

        //Laravel collection
        if (
            is_object($object) &&
            $object instanceof \Illuminate\Support\Collection &&
            $object->count() > 0            
        ) {
            return true;
        }

        //Laravel paginator
        if (
            is_object($object) &&
            $object instanceof \Illuminate\Pagination\LengthAwarePaginator &&
            count($object) > 0          
        ) {
            return true;
        }

        return false;
    }
1 Answers

You can use the isEmpty() method link. Or in Blade you can use the @forelse directive which is basically foreach with an if link

Edit 1: I just realized that you said you can also get null as a value. Then a solution is:

forelse($var ?? [] as $varItem)

@empty

@endforelse 
Related