Home > Net >  Showing empty result of non-object value when parsing data in Javascript
Showing empty result of non-object value when parsing data in Javascript

Time:10-24

I'm using Laravel with Sweetalert and I tried to show a custom popup message which is showing a value of Laravel variable:

      $(document).on('click', '#custombtn', function(e) {
            e.preventDefault();
            let form = $(this).parents('form');
            swal(
                {
                    title: "Alert!",
                    text: "Youre wallet balance is: {!! digits2persian(json_decode($user_wallet->balance)) !!}",
                    type: "warning",
                    allowEscapeKey: false,
                    allowOutsideClick: false,
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "Yes",
                    cancelButtonText: "No",
                    showLoaderOnConfirm: true,
                    closeOnConfirm: false
                }).then((isConfirm) => {
                if (isConfirm.value === true) {
                    window.location.href = {!! json_encode(route('courseRegistrationWithWallet', ['course'=>$item->cor_id,'wallet'=>$user_wallet->id ?? ''])) !!}
                }
                return false;
            });
        });

But now the problem is, when $user_wallet->balance is returning null, this error will occurs:

Trying to get property 'balance' of non-object

So I tried this to show empty result, if the variable is not set:

{!! digits2persian(json_decode($user_wallet->balance)) ?? '' !!}

But didn't solve this problem and the error still appears!

So how to fix this issue?

CodePudding user response:

Read the error message carefully:

Trying to get property 'balance' of non-object

It is not the balance which is null, but the thing containing the balance. So you need to handle $user_wallet being null, e.g.:

isset($user_wallet) ? digits2persian(json_decode($user_wallet->balance)) : 'No wallet'

CodePudding user response:

try this if($user_wallet->balance > 0){}

or this $user_wallet->balance ?? "0"

  • Related