HashtagFollowController.php 1.4 KB

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