5 years ago

Best way to get collection with calculated column related to Auth::user()

Posted 5 years ago by cmarfil


I have a user following system like twitter:

 //User following relationship
 public function follows(){
   return $this->belongsToMany('User', 'user_follows', 'user_id', 'follow_id')-  >withTimestamps();

 //User followers relationship
 public function followers(){
   return $this->belongsToMany('User', 'user_follows', 'follow_id', 'user_id');

Now in views, I always need to know if the authenticated user is following users that are shown on screen with attribute like "$user->imFollowing"


$bestUsers = User::paginate(12);


@foreach($bestUsers as $user)

 <div class="user">
  <p>{{ $user->username }}</p>
   <p><a class="follow" data-userid="{{ $user->id }}" href="#">Follow user</a></p>


How to get a collection of users and implement attribute "imFollowing" related with Auth::user()?

*Now i'm using:

@if(Auth::user()->follows->contains($user->id)) Following @else Follow @endif


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