spoon
638
6
Laravel

Listing friends of a user

Posted 3 years ago by spoon

Hi, I'm trying to list all friends of a user, but I'm stuck.

users table

user_id
name
etc.

friendship table

friendship_id
friend_one (user_id as foreign key)
friend_two (user_id as foreign key)

User.php Model (I removed everything but relationship)

<?php namespace App\Models;

class User {
    public function friends() {
        return $this->belongsToMany('\App\Models\Friendship', 'friendship','friend_one', 'friend_two');
    }

UserController.php

$friends = Friendship::where('friend_one', Auth::user()->user_id)->friends;
return view('test')->with('friends', $friends);

View

@foreach($friends as $friend)
    {{$friend->user_id}}
@endforeach

Here's the error I got : Undefined property: Illuminate\Database\Eloquent\Builder::$friends

Please sign in or create an account to participate in this conversation.