Reputation: 11
I want delete a post with authorization but failed with error "message": false, "errors": "This action is unauthorized."
destroy 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;
}
Upvotes: 1
Views: 466
Reputation: 381
Ensure that the user is good connected. Which api do you used.? 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.
You can also check the value by debbuging like this, and look at the response.
var_dump($post->user_id);
var_dump($user);
die();
Upvotes: 1