php – Laravel动作未经授权
我正在尝试删除属于创建它的用户的帖子,但是我收到此错误(顺便说一下,这是在网络日志中)
我正在使用laravel 5.5 policy,不确定我是否正确行事,我在我的AuthServiceProvider中注册了$protected policies Post :: class => PostPolicy ::类, 路线 Route :: delete(‘auth / post / {id}’,’PostController @ destroy’); PostPolicy.php <?php namespace AppPolicies; use AppUser; use AppPost; use IlluminateAuthAccessHandlesAuthorization; class PostPolicy { use HandlesAuthorization; /** * Determine whether the user can view the post. * * @param AppUser $user * @param AppPost $post * @return mixed */ public function view(User $user,Post $post) { // } /** * Determine whether the user can create posts. * * @param AppUser $user * @return mixed */ public function create(User $user) { // } /** * Determine whether the user can update the post. * * @param AppUser $user * @param AppPost $post * @return mixed */ public function update(User $user,Post $post) { // } /** * Determine whether the user can delete the post. * * @param AppUser $user * @param AppPost $post * @return mixed */ public function delete(User $user,Post $post) { // return $user->id === $post->user_id; } PostController.php(此文件有更多代码,但我想突出显示删除功能) <?php namespace AppHttpControllers; use AppPost; use AppUser; use AppPoliciesTaskPolicy; use IlluminateHttpRequest; use IlluminateHttpResponse; class PostController extends Controller { public function destroy($id,Post $post) { $mypost = $this->authorize('delete',$post); if($mypost){ Post::destroy($id); } } } Main.js删除帖子 $scope.deletePost = function(post){ var index = $scope.myposts.indexOf(post); if(index != -1){ $scope.myposts.splice(index,1); } $http.delete('auth/post/' + post.id); }; HTML <button ng-click="deletePost(post)">x</button> 之前 后 解决方法
你不需要检索帖子,让Laravel为你做这件事.
编辑您的路线如下: Route :: delete(‘auth / post / {post}’,’PostController @ destroy’); 请注意,大括号之间的帖子将是Laravel找到的分配给帖子的变量名称.如果没有找到帖子,Laravel将返回Not Found 404. 然后在你的控制器中,你必须告诉Laravel你期望有一个帖子通过这条路线: 方法符号将是这样的:destroy(Post $post). $post是您路线中的{post}. 最后,对于授权,您将无法获得授权方法返回的帖子.您将Laravel找到的$post传递给authorize方法. 这是完整的方法: public function destroy(Post $post) { $this->authorize('delete',$post); if ($post->delete()) { return response()->json(['message' => 'deleted']); }; return response()->json(['error' => 'something went wrong'],400); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |