-
php教程之使用Laravel集成JWT认证开发RestfulApi(7)
在 app/Http/Controllers 目录下打开 ProductController.php 文件。在文件开头添加 use 指令覆盖上一个。
1
2
3
|
use App\Product; use Illuminate\Http\Request; use JWTAuth; |
现在我们将实现五个方法。
index, 为经过身份认证的用户获取所有产品列表
show, 根据 ID 获取特定的产品
store, 将新产品存储到产品列表中
update, 根据 ID 更新产品详情
destroy, 根据 ID 从列表中删除产品
添加一个构造函数来获取经过身份认证的用户,并将其保存在 user 属性中。
1
2
3
4
5
|
protected $user; public function __construct() { $ this ->user = JWTAuth::parseToken()->authenticate(); } |
parseToken 将解析来自请求的令牌, authenticate 通过令牌对用户进行身份验证。
让我们添加 index 方法。
1
2
3
4
5
6
7
|
public function index() { return $ this ->user ->products() -> get ([ 'name' , 'price' , 'quantity' ]) ->toArray(); } |
上面的代码非常简单,我们只是使用 Eloquent 的方法获取所有的产品,然后将结果组成一个数组。最后,我们返回这个数组。Laravel 将自动将其转换为 JSON ,并创建一个为 200 成功的响应码。
继续实现 show 方法。
1
2
3
4
5
6
7
8
9
10
11
|
public function show($id) { $product = $ this ->user->products()->find($id); if (!$product) { return response()->json([ 'success' => false , 'message' => 'Sorry, product with id ' . $id . ' cannot be found' ], 400); } return $product; } |