Skip to content

Commit c24fd69

Browse files
author
qiang.sun
committed
文章列表API接口
1 parent 4cf55db commit c24fd69

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
namespace App\Http\Controllers\API;
4+
5+
use App\Models\Post;
6+
use Illuminate\Http\Request;
7+
use App\Http\Controllers\Controller;
8+
9+
class PostController extends Controller
10+
{
11+
public function index(Request $request)
12+
{
13+
// 每页显示5条记录
14+
$posts = Post::orderBy('published_at', 'desc')->simplePaginate(5);
15+
$items = [];
16+
foreach ($posts->items() as $post) {
17+
$item['id'] = $post->id;
18+
$item['title'] = $post->title;
19+
$item['summary'] = $post->subtitle;
20+
$item['thumb'] = config('blog.uploads.webpath') . '/' . $post->page_image;
21+
$item['posted_at'] = $post->published_at;
22+
$item['views'] = mt_rand(1, 10000); // 暂时没有实现文章浏览数逻辑,返回随机数
23+
$items[] = $item;
24+
}
25+
$data = [
26+
'message' => 'success',
27+
'articles' => $items
28+
];
29+
return response()->json($data);
30+
}
31+
}

routes/api.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
| is assigned the "api" middleware group. Enjoy building your API!
1313
|
1414
*/
15+
Route::middleware('throttle:60,1')->prefix('v1')->group(function() {
16+
Route::get('/articles', 'API\PostController@index');
17+
});
1518

1619
Route::middleware('auth:api')->get('/user', function (Request $request) {
1720
return $request->user();

0 commit comments

Comments
 (0)