質問するログイン新規登録

質問編集履歴

1

初心者マーク

2020/04/12 21:00

投稿

tenlife
tenlife

スコア70

title CHANGED
File without changes
body CHANGED
@@ -9,16 +9,35 @@
9
9
  ```controller
10
10
  public function follow(User $user)
11
11
  {
12
- // $follower = Auth::user();
12
+ $follower = Auth::user();
13
- // $is_following = $follower->isFollowing($user->id);
13
+ $is_following = $follower->isFollowing($user->id);
14
- // if(!$is_following){
14
+ if(!$is_following){
15
- // $follower->follow($user->id);
16
- // }
17
- // 下記が動くコード
18
-      Auth::user()->follow($user->id);
15
+ $follower->follow($user->id);
16
+ }
17
+      return back();
19
18
  }
19
+ public function unfollow(User $user)
20
+ {
21
+
22
+ $follower = Auth::user();
23
+ $is_following = $follower->isFollowing($user->id);
24
+ if(!$is_following){
25
+ $follower->unfollow($user->id);
26
+ }
27
+
28
+ return back();
29
+ }
20
30
  ```
21
31
  ```User
32
+ public function followers()
33
+ {
34
+ return $this->belongsToMany(self::class, 'follows', 'followed_id', 'following_id');
35
+ }
36
+
37
+ public function follows()
38
+ {
39
+ return $this->belongsToMany(self::class, 'follows', 'following_id', 'followed_id');
40
+ }
22
41
  // フォローする処理
23
42
  public function follow(Int $user_id)
24
43
  {
@@ -42,6 +61,18 @@
42
61
  return $this->followers()->where('following_id', $user_id);
43
62
  }
44
63
  ```
64
+ ```Follows
65
+ <?php
66
+
67
+ namespace App;
68
+
69
+ use Illuminate\Database\Eloquent\Model;
70
+
71
+ class Follows extends Model
72
+ {
73
+ protected $fillable = ['following_id', 'followed_id'];
74
+ }
75
+ ```
45
76
  ビューでの条件分岐でもうまく判定できていません。一度フォローを外すと常にフォロー解除のボタンしか出てきません。
46
77
  データベースは削除されています。
47
78
  ```view
@@ -57,7 +88,27 @@
57
88
  </form>
58
89
  @endif
59
90
  ```
91
+ 追記
92
+ ```web
93
+ Route::post('/mypage/{user}/follows', 'UserController@follow')->name('follow');
94
+ Route::post('/mypage/{user}/unfollows', 'UserController@unfollow')->name('unfollow');
95
+ ```
96
+ ```migration
97
+ public function up()
98
+ {
99
+ Schema::create('follows', function (Blueprint $table) {
100
+ $table->bigIncrements('id');
101
+ $table->bigInteger('following_id')->unsigned();
102
+ $table->bigInteger('followed_id')->unsigned();
60
103
 
104
+ $table->foreign('following_id')->references('id')->on('users')->onDelete('cascade');
105
+ $table->foreign('followed_id')->references('id')->on('users')->onDelete('cascade');
106
+ $table->timestamps();
107
+ });
108
+ }
109
+ ```
110
+
111
+
61
112
  少し質問が雑になってしまい申し訳ありません。
62
113
 
63
114
  どなたか知恵をお借りしたいです。