JCC
JCC

Reputation: 43

Laravel 5.1 relationships, Have users ids, but i dont have they usernames

I'm a novice but I'm currently trying to build a one way friendlist relationship, as you can see I get only the userid of the users, but I need their usernames, the problem is, these ids are coming from a relationship table "friends" as results of a query, which doesn't have usernames, instead it stores users_id.

This is what i GET!

Screenshot

Here is my config

*usuarios stands for users*

table usuarios:
id->primary
username

friends table:
id->primary
user_id->reference->users.id
friend_id->reference->users.id

User model:

public function friends()
{
    return $this->belongsToMany('App\User', 'friends', 'user_id', 'friend_id');
}

Now the Routes:

/* get single user by id */
Route::get('user/{usuario}', function($usuario) {
    $usuario = DB::table('usuarios')->where('username', $usuario)->first();
    $friends = DB::table('friends')->where('user_id', '=', $usuario->id)->get();
    return view('users.profile')
        ->with('friends', $friends)
        ->with('user', $usuario);
});

Templating

<ul style="list-style-type: none">
   <li><a href="#">friends placeholder</a>
   @foreach ($friends as $friend)
      <li> {{$friend->friend_id}}</li>
   @endforeach
   </li>
</ul>

said that, I want to see my friend's friends.

Thank you very much! Tell me if Im missing something.

Upvotes: 1

Views: 368

Answers (1)

BrokenBinary
BrokenBinary

Reputation: 7879

You can use a join to select the User model associated with each friend_id.

In your route, replace your $friends = ... line with this:

$friends = DB::table('usuarios')
             ->join('friends', 'friends.friend_id', '=', 'usuarios.id')
             ->where('friends.user_id', '=', $usuario->id)
             ->get();

This will return the collection of Users who are friends with $usuario

But there is a better way.

If you're using Eloquent you can take advantage of eager loading and do this:

Route:

Route::get('user/{usuario}', function($usuario) {
    $usuario = \App\User::with('friends')
                   ->where('username', $usuario)
                   ->firstOrFail();

    return view('users.profile')->with('user', $usuario);
});

Template:

<ul style="list-style-type: none">
    <li><a href="#">friends placeholder</a>
        @foreach ($user->friends as $friend)
            <li>{{ $friend->username }}</li>
        @endforeach
    </li>
</ul> 

Upvotes: 2

Related Questions