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

Posted 4 years ago by cmarfil

Hello,

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"

Controller:

...
$bestUsers = User::paginate(12);
....

View:

@foreach($bestUsers as $user)

 <div class="user">
  <p>{{ $user->username }}</p>
  @if($user->imFolling) 
   <p>Following</p>
  @else 
   <p><a class="follow" data-userid="{{ $user->id }}" href="#">Follow user</a></p>
  @endif
 </div>

@endforeach

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

Thanks!

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

Reply to

Use Markdown with GitHub-flavored code blocks.