简体   繁体   English

删帖授权 Laravel API

[英]Delete Post Authorize Laravel API

I want delete a post with authorization but failed with error "message": false, "errors": "This action is unauthorized."我想删除经过授权的帖子,但因错误“消息”而失败:false,“错误”:“此操作未经授权。”

destroy controller销毁 controller

public function destroy($id, Post $post)
{
    try {
        $this->authorize('delete', $post);
        $posts = Post::find($id);
        $posts->delete();
        return response()->json([
            'success' => true,
            'message' => 'Success'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'message' => false,
            'errors' => $e->getMessage()
        ]);
    }

}

policy政策

public function delete(User $user, Post $post)
{
    return $user->id == $post->user_id;
}

Postman Postman

Ensure that the user is good connected.确保用户连接良好。 Which api do you used.?你用的是哪个api? If sanctum or passport, you need to specified in your Header Request on Postman, attribute Authorization with the value Bearer your_token That will create a request like you where connected as the user who owns the token.如果是圣所或护照,您需要在 Postman 上的 Header 请求中指定,属性Authorization的值为Bearer your_token这将创建一个像您这样的请求,作为拥有令牌的用户连接。 You can also check the value by debbuging like this, and look at the response.您也可以通过像这样调试来检查值,并查看响应。

var_dump($post->user_id);
var_dump($user);
die();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM