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