Gilko
Gilko

Reputation: 2387

Laravel 4 : getting username instead of id in the index view, Many to Many Relationship

I have a friend_users table where I store user_id's from users. Now I want to see who are myfriends, but I don't know how to access the user_username's using eloquent.

index view :

@foreach($friend_users as $friend_user)
    <tr>
       <td>{{ $friend_user->friend_user_id }}</td>  
       <td>{{ $friend_user->user->user_username }}</td>
       <td>{{ $friend_user->friend->user_username }}</td>
    </tr>
@endforeach

index controller :

public function index()
    {
        $friend_users = FriendUser::all();

        return View::make('friend_users.index')
            ->with('friend_users', $friend_users);
    }

User model :

public function users(){
        return $this->belongsToMany('User', 'friend_users', 'friend_id', 'user_id');
    }

FriendUser model :

public function friend() 
{ 
    return $this->belongsTo('User', 'friend_id'); 
}

public function user() 
{ 
    return $this->belongsTo('User', 'user_id'); 
}

Upvotes: 0

Views: 914

Answers (1)

c-griffin
c-griffin

Reputation: 3026

Assuming you have these relations set up in your FriendUser model

public function user() { return $this->belongsTo('User'); }
public function friend() { return $this->belongsTo('User', 'friend_id'); }

You can eager load your user model(s) (in your controller):

$friend_users = FriendUser::with('user', 'friend')->where('user_id', $yourUserId);

return View::make('friend_users.index', array('friend_users', $friend_users));

And in your view:

@foreach($friend_users as $friend_user)
    <tr>
        // the user info
        <td>{{ $friend_user->user->id}}</td> 
        <td>{{ $friend_user->user->name}}</td>
        // the friend info
        <td>{{ $friend_user->friend->id }}</td>  
        <td>{{ $friend_user->friend->name }}</td>
    </tr>
@endforeach

By the sound of it, this should suffice for your purpose, but if user_id and friend_id can be interchangeable, you may want to consider a many to many relationship instead.

http://laravel.com/docs/eloquent#many-to-many

Upvotes: 1

Related Questions