0
在laravel我有一个跟随者表,我用它来检查用户是否正在浏览另一个用户,以及他是否可以对帖子发表评论。试图写Laravel的帖子评论的政策
表是这样的:
Schema::create('followers', function (Blueprint $table) {
$table->unsignedInteger('publisher_id')->unsigned();
$table->unsignedInteger('follower_id')->unsigned();
$table->boolean('enable_follow')->default('1');
$table->unique(['publisher_id', 'follower_id']);
$table->timestamps();
$table->foreign('publisher_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('follower_id')
->references('id')
->on('users')
->onDelete('cascade');
});
,这些都是我做决定,如果用户可以评论一个帖子的检查:
public function canComment(User $user, Post $post)
{
$following = Follower::where('follower_id', $user->id)->where('publisher_id', $post->user_id)->select('enable_follow')->get();
if (!$following->isEmpty()) {
$enabled = $following[0]['enable_follow'];
if ($enabled != '0') {
return true;
} else {
return false;
}
} else if ($following->isEmpty()) {
return true;
}
}
这是用于存储控制器部分,你可以看到我试图授权这样的:$this->authorize('canComment', $post[0]);
public function store(Request $request)
{
//on_post, from_user, body
// define rules
$rules = array(
'post_id' => 'required',
'body' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
$post_id = $request->input('post_id');
$post = Post::findOrFail($post_id);
if ($validator->fails()) {
return Response()->json($validator);
} else {
$this->authorize('canComment', $post);
//prepares object to be stored in DB
$comment = new Comment();
$comment['user_id'] = $request->user()->id;
$comment['post_id'] = $post_id;
$comment['body'] = $request->input('body');
$comment->save();
if ($comment) {
$comment['user_name'] = $request->user()->username;
$comment['comment_id'] = $comment->id;
$comment['token'] = $request->input('_token');
}
return Response()->json($comment);
}
}
在p这里的问题是我在出现$following
空的情况下以及在哪里启用后出现403(禁止)错误。该政策未按预期工作。在门门面的授权方法
的源代码:
public function authorize($ability, $arguments = [])
{
$result = $this->raw($ability, $arguments);
if ($result instanceof Response) {
return $result;
}
return $result ? $this->allow() : $this->deny();
}
也许我没有正确的政策,因为这代码returing真或假的希望得到的结果是instance of Response
还等什么呢,你回授或拒绝访问?
你把你的'canComment'方法和巫婆laravel你使用? – Maraboc
它在控制器中,你没有在代码中看到它吗? – Chriz74
我的意思是'公共功能canComment(用户$用户,发布$后)...'巫婆**拉拉维尔你使用**? – Maraboc