0%

PHP Laravel 系列 - (10) API開發_Read

1. 簡易API

當前後端配合的時候,可以利用這種方式提供資料給前端去call

2. 簡單建一個假資料

我們新增一個getData()函式

1
2
3
4
5
6
7
8
9
10
11
12
13
public function getData()
{
return [
[
'title' => 'A',
'content' => 'aaa',
],
[
'title' => 'B',
'content' => 'bbb',
]
];
}

然後在加在index function

1
2
3
4
public function index(Request $request)
{
return response($this->getData());
}

ProductController.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = $this->getData();
return response($data);
}

public function getData()
{
return [
[
'title' => 'A',
'content' => 'aaa',
],
[
'title' => 'B',
'content' => 'bbb',
]
];
}
}

3. POSTMAN測試

測試url

1
http://localhost:8000/products

image-20211017013907351