public function edit($id)
{
$post = Post::find($id);
if (!$post) {
abort(403);
}
if (!Auth::user() || Auth::user()->id != $post->user_id) {
return redirect()->route('home');
}
return view('post-edit',compact('post'));
}
Laravel: How to throw 403 if the user enter the ID manually in the route? Ask Question up vote
Building an app (Blog/posts). Where only auth users can edit their post(which ofcourse belongs to them only). For example, Post with an id of 15 belongs to particular user, so if he edits it, the route will be like this
http://localhost:8000/post/15/edit
this is correct.
But when the user enters any other post ID(which doesn't belongs to him) in the route, it shows
http://localhost:8000/post/16/edit
ErrorException (E_NOTICE)
Trying to get property 'user_id' of non-object
How to show unauthorised page in this case?
This is the postController
public function edit($id)
{
$post = Post::find($id);
if(Auth::user()->id == $post->user_id){
return view('post-edit',compact('post'));
}else {
return redirect()->route('home');
} }
Personally I'd use
// if post isn't found by $id, show 404
$post = Post::findOrFail($id);
// if user isn't owner of post, show 403
if (!Auth::user() || Auth::user()->id != $post->user_id) {
abort(403);
}
return view('post-edit',compact('post'));
If the post isn't found, it should 404 because the resource doesn't exist. That's more appropriate for that scenario, and doesn't have anything to do with whether the user can edit or not. The 403 should be triggered when checking whether they are authorized or not.
The 403 (Forbidden) status code indicates that the server understood the request but
refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any). Thus, a 403 might now mean about anything.
The HTTP 404, 404 Not Found and 404 error message is a Hypertext Transfer Protocol (HTTP) standard response code, in computer network communications, to indicate that the client was able to communicate with a given server, but
the server could not find what was requested.
Please or to participate in this conversation.