■出来た方法
以下のようにすることで存在チェックが可能。
if($user->friends->where('friend_id',$friend_id)->first()){
return $this->show($friend_id);
}
※追記
コメントでご指摘ありましたが、以下のようにisEmpty()
使って出来ます。
if(!$user->friends->where('friend_id',$friend_id)->isEmpty()){
return $this->show($friend_id);
}
■ダメだった方法
1.以下のように書くと、データが存在する場合は問題無いが、データが無い場合にexists()
という関数は無いよって怒られる。
if($user->friends->where('friend_id',$friend_id)->first()->exists()){
return $this->show($friend_id);
}
2.リレーション先のデータが複数の場合にエラーになる
※取得したデータがコレクションクラスになってしまうのでexists()
とか無いよ、って怒られた
if($user->friends->where('friend_id',$friend_id)->exists()){
return $this->show($friend_id);
}
以上。