我正在尝试删除属于创建它的用户的帖子,但是我收到此错误(顺便说一下,这是在网络日志中)
“/Applications/MAMP/htdocs/eli42/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.PHP”
line : 201 message : “This action is unauthorized.” trace : [{,…},…]
我正在使用laravel 5.5 policy,不确定我是否正确行事,我在我的AuthServiceProvider中注册了$protected policies
Post :: class => PostPolicy ::类,
路线
Route :: delete(‘auth / post / {id}’,’PostController @ destroy’);
PostPolicy.PHP
<?PHP
namespace App\Policies;
use App\User;
use App\Post;
use Illuminate\Auth\Access\HandlesAuthorization;
class PostPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the post.
*
* @param \App\User $user
* @param \App\Post $post
* @return mixed
*/
public function view(User $user, Post $post)
{
//
}
/**
* Determine whether the user can create posts.
*
* @param \App\User $user
* @return mixed
*/
public function create(User $user)
{
//
}
/**
* Determine whether the user can update the post.
*
* @param \App\User $user
* @param \App\Post $post
* @return mixed
*/
public function update(User $user, Post $post)
{
//
}
/**
* Determine whether the user can delete the post.
*
* @param \App\User $user
* @param \App\Post $post
* @return mixed
*/
public function delete(User $user, Post $post)
{
//
return $user->id === $post->user_id;
}
PostController.PHP(此文件有更多代码,但我想突出显示删除功能)
<?PHP
namespace App\Http\Controllers;
use App\Post;
use App\User;
use App\Policies\TaskPolicy;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
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);
}