【发布时间】:2018-06-27 14:11:27
【问题描述】:
构建应用程序(博客/帖子)。 只有授权用户可以编辑他们的帖子(当然只属于他们)。 比如 id 为 15 的 Post 属于特定用户,所以如果他编辑它,路由会是这样的
http://localhost:8000/post/15/edit
这是正确的。
但是当用户在路由中输入任何其他帖子ID(不属于他)时,它会显示
http://localhost:8000/post/16/edit
ErrorException (E_NOTICE)
Trying to get property 'user_id' of non-object
这种情况下如何显示未经授权的页面?
这是 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');
}
}
【问题讨论】:
-
404 is page not found - 您正在寻找 403 禁止。为此,类似于;
if ($post_author != $current_user) { exit("Error msg"); }- 我不知道你的变量,所以这是对合理名称的猜测 -
好的。谢谢!但是在这种情况下如何抛出 403 呢?
-
您在此实例中遇到的错误是说您在代码中访问的变量 (
$user_id) 在您从中访问它的类中不存在 - 请确保已声明并设置它 -
我已经编辑了我的问题并添加了 PostController