HashtagFollowController.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Auth;
  5. use App\{
  6. Hashtag,
  7. HashtagFollow,
  8. Status
  9. };
  10. use App\Services\HashtagService;
  11. class HashtagFollowController extends Controller
  12. {
  13. public function __construct()
  14. {
  15. $this->middleware('auth');
  16. }
  17. public function store(Request $request)
  18. {
  19. $this->validate($request, [
  20. 'name' => 'required|alpha_num|min:1|max:124|exists:hashtags,name'
  21. ]);
  22. $user = Auth::user();
  23. $profile = $user->profile;
  24. $tag = $request->input('name');
  25. $hashtag = Hashtag::whereName($tag)->firstOrFail();
  26. $hashtagFollow = HashtagFollow::firstOrCreate([
  27. 'user_id' => $user->id,
  28. 'profile_id' => $user->profile_id ?? $user->profile->id,
  29. 'hashtag_id' => $hashtag->id
  30. ]);
  31. if($hashtagFollow->wasRecentlyCreated) {
  32. $state = 'created';
  33. HashtagService::follow($profile->id, $hashtag->id);
  34. // todo: send to HashtagFollowService
  35. } else {
  36. $state = 'deleted';
  37. HashtagService::unfollow($profile->id, $hashtag->id);
  38. $hashtagFollow->delete();
  39. }
  40. return [
  41. 'state' => $state
  42. ];
  43. }
  44. public function getTags(Request $request)
  45. {
  46. return HashtagFollow::with('hashtag')->whereUserId(Auth::id())
  47. ->inRandomOrder()
  48. ->take(3)
  49. ->get()
  50. ->map(function($follow, $k) {
  51. return $follow->hashtag->name;
  52. });
  53. }
  54. }