Can't change eloquence of relationship in Laravel
In my Laravel application I am currently working on allowing users to "block" other users.
In my user model, I'm trying to define a "locked" relationship between users:
public function blockedOfMine() {
return $this->belongsToMany('CommendMe\Models\User', 'blocked', 'user_id', 'blocked_id');
}
public function blockedBy() {
return $this->belongsToMany('CommendMe\Models\User', 'blocked', 'blocked_id', 'user_id');
}
public function blocked() {
return $this->blockedOfMine()->get();
}
public function blockedMe() {
return $this->blockedBy()->get();
}
public function isBlocked(User $user) {
return (bool) $this->blocked()->where('id', $user->id)->count();
}
public function hasBlockedMe(User $user) {
return (bool) $this->blockedMe()->where('id', $user->id)->count();
}
Basically, this model only tries to figure out if the user has blocked another user (isBlocked function) or if the user has been blocked by another user (hasBlockedMe function).
Now the first function works just fine, however the second does not, despite the fact that they are exactly the same:
if (Auth::user()->isBlocked($user)) {
return redirect()->back()->with('info', 'You cannot message blocked users.');
}
if (Auth::user()->hasBlockedMe($user)) {
return redirect()->back()->with('info', 'This user has blocked communications with you.');
}
so if I try to tell a user who is blocked, I get the message "You cannot block users." But the message goes fine when I try to inform the user who blocked me.
What am I doing wrong?
+3
source to share
1 answer