我有用户做的帖子和一个按钮,打开一个模式,用户可以编辑的帖子。
我目前有一个按钮,它有一个data-id
,并将id传递给模态,然后在模态中设置更新id,并在提交时提交。
这是一个问题,因为如果用户输入另一个id,比如400
,而不是那个可能是50
的帖子id,该怎么办?
我如何确保只更新/传递该id。
发布于 2018-01-22 04:09:06
您需要获取post-id的hidden input tag
,并且服务器端检查post的user_id是否等于登录用户的id,然后只更新post。
public function update(Request $request,$id){
$post=Post::find($id);
if($post){
if($post->user_id == auth()->user()->id){
// update post
}else{
// a person can not update post , redirect or show error
}
}else{
return view('error404'); // post not found,show 404 error page
}
}
发布于 2018-01-22 05:43:27
如果您使用Illuminate\Foundation\Http\FormRequest
执行验证,则可以使用authorize
方法。
表单请求类还包含一个authorize方法。在此方法中,您可以检查经过身份验证的用户是否具有更新给定资源的权限。
假设你的路线是...
Route::get('posts/edit/{post}', ['uses' => "PostController@update"]);
然后在您的PostRequest
中,添加一个authorize方法来验证编辑帖子的用户。
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
$post = Post::find($this->route('post'));
return $post && $this->user()->can('update', $post);
}
如果希望在authorize方法失败时自定义响应,可以覆盖failedAuthorization()
函数。
/**
* Handle a failed authorization attempt.
*
* @return void
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
protected function failedAuthorization()
{
// Spank user.
throw new AuthorizationException('This action is unauthorized.');
}
https://stackoverflow.com/questions/48374425
复制相似问题