1
votes

I'm trying to show a list of contacts for the logged in user. But obviously I'm doing something wrong.

I get a error on the contacts list page:

Trying to get property 'name' of non-object

User.php

public function contacts()
    {
        return $this->belongsToMany(Contact::class);
    }


Contact.php

public function users()
    {
        return $this->belongsToMany(User::class);
    }


ContactsController.php

public function index()
    {
        //
        $user = Auth::user();
        $user_contacts = $user->contacts()
        return view('contacts.list')->with('contacts', $user_contacts);
    }

list.blade.php

@foreach ($contacts as $contact)
    * {{ $contact->name }} <br>
@endforeach


Table schema:
contacts:
  • id
  • created_at
  • updated_at
  • name
  • address

users:

  • id
  • name
  • password
  • remember_token
  • created_at
  • updated_at

contact_user:

  • contact_id
  • user_id
3
Your User.php doesn't have any contacts() relation function - Nitish Kumar
Mistake, corrected - Biswajit Chopdar
$user_contacts = $user->contacts() must be $user_contacts = $user->contacts. - ako

3 Answers

2
votes

If you want to access pivot properties of your many to many relationship table u can access with pivot

    @foreach ($contacts as $contact)
       * {{ $contact->pivot->name }} <br>
    @endforeach

Also creates a relatioship between contact and users

public function contacts()
{
    return $this->belongsToMany(Contat::class)->withPivot(['your', 'pivot','columns']);

}

Hope this helps

1
votes

In your controller you have the following;

public function index()
{
    $user = Auth::user();
    $user_contacts = $user->contacts()
    return view('contacts.list')->with('contacts', $user_contacts);
}

It needs to be the following;

public function index()
{
    $user = Auth::user();
    $user_contacts = $user->contacts
    return view('contacts.list')->with('contacts', $user_contacts);
}

Using $user->contacts()(method) will return an instance of the query builder for that relationship, where as $user->contacts(property) will return a collection with results from a select query.

0
votes

You must return your pivot table's data in the relation as below:

public function contacts()
{
    return $this->belongsToMany(Contat::class)->withPivot(['your', 'pivot','columns']);

}

And you must get relation data like below:

$user_contacts = $user->contacts // Not $user->contacts()