Laravel 5.1 relationships, Have users ids, but i dont have they usernames -
i'm novice i'm trying build 1 way friendlist relationship, can see userid of users, need usernames, problem is, these ids coming relationship table "friends" results of query, doesn't have usernames, instead stores users_id.
this get!
here config
*usuarios stands 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 routes:
/* single user 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 $friend) <li> {{$friend->friend_id}}</li> @endforeach </li> </ul>
said that, want see friend's friends.
thank much! tell me if im missing something.
you can use join select user model associated each friend_id
.
in route, replace $friends = ...
line this:
$friends = db::table('usuarios') ->join('friends', 'friends.friend_id', '=', 'usuarios.id') ->where('friends.user_id', '=', $usuario->id) ->get();
this return collection of users friends $usuario
but there better way.
if you're using eloquent can take advantage of eager loading , 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 $friend) <li>{{ $friend->username }}</li> @endforeach </li> </ul>
Comments
Post a Comment