return the response
you are missing return on the last line
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi, I have created API endpoints using Passport for authorization and API resource feature. My goal is to allow everyone get api/books and api/books/book but only authorized users can update and delete. This is the code I am working with in BookController
public function __construct()
{
$this->middleware('auth:api')->except(['index', 'show']);
}
public function destroy(Book $book)
{
$book->delete();
return response()->json(null, 204);
}
Right now any logged in user can delete any book. What I want is to allow delete only if the logged in user()->id === book->user_id, so I have modified my code like so
public function destroy(Request $request, Book $book)
{
// Delete book only if user_id matches book's user_id
if ($request->user()->id === $book->user_id) {
$book->delete();
return response()->json(null, 204);
} else {
response()->json(['error' => 'You do not have the permission for this operation'], 403);
}
}
When I delete a book owned by the logged in user, the operation is successful and 204 status code is returned. But if the book doesn't belong to the user, i get a 200 ok status and book is not deleted. I want to display the error message in this case.
How do I fix it?
return the response
you are missing return on the last line
Please or to participate in this conversation.