public function update (Request $request, $id, $commentid) {
$this->validate($request, [
'body' =>'required|max:255'
]);
$post = Post::findorFail($id);
$comment = Comment::find($commentid);
$body = $request->body;
$comment->post_id = $post->id;
$comment->body = $body;
$comment ->user_id = Auth::user()->id;
$comment ->save();
return response()->json(['data' => $comment], 200, [], JSON_NUMERIC_CHECK);
}
如何限制其他user->id
更新auth->id
注释并使用post的select方法捕获特定post的user_id
,但得到errorexception并且使用了中间件,但是错误仍然是相同的
如果我正确理解你的问题,你可以试着这样做:
public function update (Request $request, $id, $commentid) {
$comment = Comment::find($commentid);
if ( Auth::user()->id !== $comment->user_id ) {
return response()->json(['error' => 'Forbidden'], 403);
}
// other code
}
我希望,这个决定对你来说已经足够了,但我不得不说,我更喜欢FormRequest
中的抽象验证和权限检查逻辑
https://laravel.com/docs/5.8/validation#form-请求验证
在rules()
函数中,您可以设置验证规则。在authorize()
中,检查用户是否可以更改注释。
您正在使用Auth::user((;授权给用户。验证用户是laravel的默认功能