LoginSignup
3
5

More than 5 years have passed since last update.

Laravelでリレーション(hasMany)先のデータの存在チェックを行う(出来た方法、ダメだった方法)

Last updated at Posted at 2017-09-15

■出来た方法

以下のようにすることで存在チェックが可能。

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);
}

以上。

3
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5