Solved by modyfing to $idsWhoOtherUserFollows = $otherUser->followedUsers()->lists('publisher_id')->toArray();
However now I am asing myself if there's a new more correct way to check that needle against the array of following users.
Trying to check if a user is followed by another user
Looking at the Larabook series I decided to try the method that the author uses to check if an user is followed by another user. I need this also to write a policy to allow Follows, posting etc... So in my User Model I got these lines:
/**
*
* Get the list of users that the current user follows.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function followedUsers()
{
return $this->belongsToMany( self::class, 'follows', 'follower_id', 'publisher_id')->withTimestamps();
}
/**
*
* Get the list of users who follow the current user.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function followers()
{
return $this->belongsToMany( self::class, 'follows', 'publisher_id', 'follower_id')->withTimestamps();
}
/**
*
* Determine if the user is being followed by current user
*
* @param User $otherUser
* @return bool
*/
public function isFollowedBy(User $otherUser)
{
$idsWhoOtherUserFollows = $otherUser->followedUsers()->lists('publisher_id');
return in_array($this->id, $idsWhoOtherUserFollows);
}
In my view I put a check to see if the Policy works like this:
@can('temp_check', $i)
$i are the posts from a User that I am showing in the page. I am using this check to allow a user to Post a comment or Follow the user
The policy is like this, please remember that I am using this only to test if it's working:
public function temp_check(User $user, Post $post)
{
$Publisher = User::find($post->user_id);
if($Publisher->isFollowedBy($user)){
dd($user);
}
else{
dd("no cigar");
}
What happens then is if I load the page I got this error exception:
ErrorException in User.php line 144:
in_array() expects parameter 2 to be array, object given
So Line 144 is this:
return in_array($this->id, $idsWhoOtherUserFollows);
So I guess that $ $idsWhoOtherUserFollows is being returned as Object by $otherUser->followedUsers()->lists('publisher_id');
So the code from the series is not working, is that because Laravel 5.1 behaves differently from 4.3 ? How would you correct that?
Indeed that's a Collection:
dd($idsWhoOtherUserFollows)
returns
Collection {#294 ▼
#items: []
}
Please or to participate in this conversation.