1234567891011121314151617181920212223242526272829303132333435363738 |
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use App\Models\Post;
- use Illuminate\Support\Facades\Redis;
- class PostController extends Controller
- {
- public function show(Post $post)
- {
- $post->increment('views');
- if ($post->save()) {
-
- Redis::zincrby('popular_posts', 1, $post->id);
- }
- return 'Show Post #' . $post->id;
- }
-
- public function popular()
- {
-
- $postIds = Redis::zrevrange('popular_posts', 0, 9);
- if ($postIds) {
- $idsStr = implode(',', $postIds);
-
- $posts = Post::whereIn('id', $postIds)
- ->select(['id', 'title', 'views'])
- ->orderByRaw('field(`id`, ' . $idsStr . ')')
- ->get();
- } else {
- $posts = null;
- }
- dd($posts->toArray());
- }
- }
|