我需要根据登录的用户限制对应用程序某些部分的访问。我的意思是让用户在博客应用程序上仅编辑自己的帖子。
如果用户不是所需帖子的所有者,是否有比 Controller 的每个功能更好的方法,重定向到某个错误页面?
例如,如果我的路线是/post/{post_id}/edit
、/post/{post_id}/preview
、/post/{post_id}/delete
,我能否以某种方式在 PostController 中声明一个通用函数,例如:
if(Post::find($post_id)->user_id != Auth::user()->id){
return View::make('access-error');
}
谢谢!
最佳答案
在你的 Controller 中你可以做这样的事情:
public $check = ['edit', 'preview', 'delete'];
public function callAction($method, $parameters) {
if(in_array($method, $this->check, true) &&
$post_id = $parameters['post_id'] &&
Post::find($post_id)->user_id != Auth::user()->id) {
return View::make('access-error');
}
return parent::callAction($method, $parameters);
}
关于php - 使用模型对象的 Laravel 访问控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31246280/