質問編集履歴

1

初心者マーク

2020/04/12 21:00

投稿

tenlife
tenlife

スコア70

test CHANGED
File without changes
test CHANGED
@@ -20,26 +20,64 @@
20
20
 
21
21
  {
22
22
 
23
- // $follower = Auth::user();
23
+ $follower = Auth::user();
24
-
24
+
25
- // $is_following = $follower->isFollowing($user->id);
25
+ $is_following = $follower->isFollowing($user->id);
26
-
26
+
27
- // if(!$is_following){
27
+ if(!$is_following){
28
-
29
- // $follower->follow($user->id);
28
+
30
-
31
- // }
32
-
33
- // 下記が動くコード
34
-
35
-      Auth::user()->follow($user->id);
29
+ $follower->follow($user->id);
30
+
31
+ }
32
+
33
+      return back();
36
34
 
37
35
  }
38
36
 
37
+ public function unfollow(User $user)
38
+
39
+ {
40
+
41
+
42
+
43
+ $follower = Auth::user();
44
+
45
+ $is_following = $follower->isFollowing($user->id);
46
+
47
+ if(!$is_following){
48
+
49
+ $follower->unfollow($user->id);
50
+
51
+ }
52
+
53
+
54
+
55
+ return back();
56
+
57
+ }
58
+
39
59
  ```
40
60
 
41
61
  ```User
42
62
 
63
+ public function followers()
64
+
65
+ {
66
+
67
+ return $this->belongsToMany(self::class, 'follows', 'followed_id', 'following_id');
68
+
69
+ }
70
+
71
+
72
+
73
+ public function follows()
74
+
75
+ {
76
+
77
+ return $this->belongsToMany(self::class, 'follows', 'following_id', 'followed_id');
78
+
79
+ }
80
+
43
81
  // フォローする処理
44
82
 
45
83
  public function follow(Int $user_id)
@@ -86,6 +124,30 @@
86
124
 
87
125
  ```
88
126
 
127
+ ```Follows
128
+
129
+ <?php
130
+
131
+
132
+
133
+ namespace App;
134
+
135
+
136
+
137
+ use Illuminate\Database\Eloquent\Model;
138
+
139
+
140
+
141
+ class Follows extends Model
142
+
143
+ {
144
+
145
+ protected $fillable = ['following_id', 'followed_id'];
146
+
147
+ }
148
+
149
+ ```
150
+
89
151
  ビューでの条件分岐でもうまく判定できていません。一度フォローを外すと常にフォロー解除のボタンしか出てきません。
90
152
 
91
153
  データベースは削除されています。
@@ -116,6 +178,46 @@
116
178
 
117
179
  ```
118
180
 
181
+ 追記
182
+
183
+ ```web
184
+
185
+ Route::post('/mypage/{user}/follows', 'UserController@follow')->name('follow');
186
+
187
+ Route::post('/mypage/{user}/unfollows', 'UserController@unfollow')->name('unfollow');
188
+
189
+ ```
190
+
191
+ ```migration
192
+
193
+ public function up()
194
+
195
+ {
196
+
197
+ Schema::create('follows', function (Blueprint $table) {
198
+
199
+ $table->bigIncrements('id');
200
+
201
+ $table->bigInteger('following_id')->unsigned();
202
+
203
+ $table->bigInteger('followed_id')->unsigned();
204
+
205
+
206
+
207
+ $table->foreign('following_id')->references('id')->on('users')->onDelete('cascade');
208
+
209
+ $table->foreign('followed_id')->references('id')->on('users')->onDelete('cascade');
210
+
211
+ $table->timestamps();
212
+
213
+ });
214
+
215
+ }
216
+
217
+ ```
218
+
219
+
220
+
119
221
 
120
222
 
121
223
  少し質問が雑になってしまい申し訳ありません。