SearchController.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Auth;
  4. use App\Hashtag;
  5. use App\Profile;
  6. use App\Status;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Support\Facades\Cache;
  9. class SearchController extends Controller
  10. {
  11. public function __construct()
  12. {
  13. $this->middleware('auth');
  14. }
  15. public function searchAPI(Request $request, $tag)
  16. {
  17. if(mb_strlen($tag) < 3) {
  18. return;
  19. }
  20. $hash = hash('sha256', $tag);
  21. $tokens = Cache::remember('api:search:tag:'.$hash, 60, function () use ($tag) {
  22. $tokens = collect([]);
  23. $hashtags = Hashtag::select('id', 'name', 'slug')->where('slug', 'like', '%'.$tag.'%')->limit(20)->get();
  24. if($hashtags->count() > 0) {
  25. $tags = $hashtags->map(function ($item, $key) {
  26. return [
  27. 'count' => $item->posts()->count(),
  28. 'url' => $item->url(),
  29. 'type' => 'hashtag',
  30. 'value' => $item->name,
  31. 'tokens' => explode('-', $item->name),
  32. 'name' => null,
  33. ];
  34. });
  35. $tokens->push($tags);
  36. }
  37. $users = Profile::select('username', 'name', 'id')->where('username', 'like', '%'.$tag.'%')->limit(20)->get();
  38. if($users->count() > 0) {
  39. $profiles = $users->map(function ($item, $key) {
  40. return [
  41. 'count' => 0,
  42. 'url' => $item->url(),
  43. 'type' => 'profile',
  44. 'value' => $item->username,
  45. 'tokens' => [$item->username],
  46. 'name' => $item->name,
  47. ];
  48. });
  49. $tokens->push($profiles);
  50. }
  51. return $tokens;
  52. });
  53. $posts = Status::select('id', 'profile_id', 'caption', 'created_at')
  54. ->whereHas('media')
  55. ->whereNull('in_reply_to_id')
  56. ->whereNull('reblog_of_id')
  57. ->whereProfileId(Auth::user()->profile->id)
  58. ->where('caption', 'like', '%'.$tag.'%')
  59. ->orderBy('created_at', 'desc')
  60. ->get();
  61. if($posts->count() > 0) {
  62. $posts = $posts->map(function($item, $key) {
  63. return [
  64. 'count' => 0,
  65. 'url' => $item->url(),
  66. 'type' => 'status',
  67. 'value' => 'Posted '.$item->created_at->diffForHumans(),
  68. 'tokens' => [$item->caption],
  69. 'name' => $item->caption,
  70. 'thumb' => $item->thumb(),
  71. ];
  72. });
  73. $tokens = $tokens->push($posts);
  74. }
  75. if($tokens->count() > 0) {
  76. $tokens = $tokens[0];
  77. }
  78. return response()->json($tokens);
  79. }
  80. }