SearchController.php 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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, 5, 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')
  38. ->whereNull('status')
  39. ->where('username', 'like', '%'.$tag.'%')
  40. ->limit(20)
  41. ->get();
  42. if($users->count() > 0) {
  43. $profiles = $users->map(function ($item, $key) {
  44. return [
  45. 'count' => 0,
  46. 'url' => $item->url(),
  47. 'type' => 'profile',
  48. 'value' => $item->username,
  49. 'tokens' => [$item->username],
  50. 'name' => $item->name,
  51. ];
  52. });
  53. $tokens->push($profiles);
  54. }
  55. return $tokens;
  56. });
  57. $posts = Status::select('id', 'profile_id', 'caption', 'created_at')
  58. ->whereHas('media')
  59. ->whereNull('in_reply_to_id')
  60. ->whereNull('reblog_of_id')
  61. ->whereProfileId(Auth::user()->profile->id)
  62. ->where('caption', 'like', '%'.$tag.'%')
  63. ->orderBy('created_at', 'desc')
  64. ->get();
  65. if($posts->count() > 0) {
  66. $posts = $posts->map(function($item, $key) {
  67. return [
  68. 'count' => 0,
  69. 'url' => $item->url(),
  70. 'type' => 'status',
  71. 'value' => "by {$item->profile->username} <span class='float-right'>{$item->created_at->diffForHumans(null, true, true)}</span>",
  72. 'tokens' => [$item->caption],
  73. 'name' => $item->caption,
  74. 'thumb' => $item->thumb(),
  75. ];
  76. });
  77. $tokens = $tokens->push($posts);
  78. }
  79. if($tokens->count() > 0) {
  80. $tokens = $tokens[0];
  81. }
  82. return response()->json($tokens);
  83. }
  84. }