phplaravel-5table-relationships

Trying to get property of non-object, can't access to phoneNumber properties


Route::get('/', function (){

$contacts = Contact::all();
//dd($contacts);

return view('welcome')->with('contacts',$contacts);

});

From the route i pass the $cotacts to the view

@foreach($contacts as  $contact)

    <li> {{$contact->name}}

        <small>by {{$contact->phoneNumber->number}}</small>

    </li>

@endforeach

but when i what to access the number of phoneNumber, this is my class:

public function phoneNumber()
    {
         return $this->hasOne(PhoneNumber::class);
    }

i get error Trying to get property of non-object ???

also when i put like this:

<li> {{$contact->name}}

            <small>by {{$contact->phoneNumber}}</small>

        </li>

i get: Colton Kilback IV by {"id":20,"contact_id":1,"number":"+1-936-288-3493","created_at":"2018-04-01 20:14:16","updated_at":"2018-04-01 20:14:16"}

Shaun Streich DVM by

Dr. Ruthe Thiel III by

Laverne Mertz by {"id":11,"contact_id":4,"number":"(769) 844-4643 x59321","created_at":"2018-04-01 20:14:16","updated_at":"2018-04-01 20:14:16"}

and so on some name don't have number.


Solution

  • The problem is that you don't have an associated PhoneNumber for your Contacts with the names Dr. Ruthe Thiel III and Shaun Streich DVM.

    You can use this in your blade template instead:

    <li> {{$contact->name}}
        <small>by {{$contact->phoneNumber->number ?? ''}}</small>
    </li>
    

    which will simply ommit the phone number if none is available.


    Edit: if you want the output to be a bit more nice, you can also use something like this:

    <li> {{$contact->name}}
        @if(count($contact->phoneNumber))
            <small>by {{$contact->phoneNumber->number}}</small>
        @else
            <small>has no known phone number</small>
        @endif
    </li>