Home > database >  How to not show empty collection
How to not show empty collection

Time:09-29

I have tried adding this code to my Blade:

@if(!empty($user_wallet))
    <li class="mt-3" id="theWallet">
        <div class="form-check">
            <input class="form-check-input" type="checkbox" name="pay_wallet" value="1" id="thisWrapper">
            <label class="form-check-label small mr-3" for="thisWrapper">
            Pay with Wallet
            </label>
        </div>
    </li>
@endif

So this means, if user has not any Wallet, do not show the div with id of theWallet.

But now the problem is, it still shows the div and checkbox however the user does not have any Wallet stored at the DB.

And when I dd($user_wallet), I get this:

Illuminate\Database\Eloquent\Collection {#2562 ▼
  #items: []
}

Meaning that, it's empty. But why it still shows the div?

CodePudding user response:

Use the isset() function with empty() function.

Replace your if condition with

@if(!empty($user_wallet))

to

@if(!empty($user_wallet) && isset($user_wallet)) 

or 

@if(isset($user_wallet))

The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL.

This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.

CodePudding user response:

Hello if $user_wallet contains the collection data then you need to change the @if condition.

Replace your

@if(!empty($user_wallet))

To

@if(!$user_wallet->isEmpty()) OR @if($user_wallet->isNotEmpty())
  • Related