Treasure Uvietobore
Treasure Uvietobore

Reputation: 131

How To Fix Error In Laravel. 'Trying To get property country of non object'

Here is the Exception Code Code In the Framework/views/profile_settings.blade.php

When my users visit their profile setting the stack trace errors always come up with the exception. Please help me out. Thanks

$('select[name=country]').val('<?php echo e($user->address->country); ?>');

Upvotes: 0

Views: 670

Answers (3)

Koushik Balo
Koushik Balo

Reputation: 97

Null Safe Operator

If you are using less version of php 8. You can write these type of code

$country = null;
    if ($user !== null) {
            if ($user->address !== null) {
                $country = $user->address->country;
            }
        }

PHP 8 allows you to write this.

$country = $user?->address?->country;

It will work like these

Helpfull Link

Upvotes: 2

OMR
OMR

Reputation: 12218

I have an address in my db but in json format, and some times comes without country.

the way I fixed this was making new property to handle this:

 public function getAddressAsStringAttribute()
    {
        if ($this->address == null) return null;
        if (is_object($this->address) && property_exists($this->address, 'country'))
            return $this->address->country;
        else
            return null;
    }

now you can use this new property like:

$('select[name=country]').val('<?php echo e($user->addressAsString); ?>');

Upvotes: 0

P. K. Tharindu
P. K. Tharindu

Reputation: 2730

$user->address is probably returning null. Try something like:

{{ $user->address->country ?? '' }}

Upvotes: 1

Related Questions