in laravel have follower table use check if user folowing user , if can comment on posts.
the table this:
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'); });
and these checks make decide if user can comment post:
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; } }
and controller part storing, can see i'm trying authorize this: $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 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); } }
the problem here 403 (forbidden) error in situation have $following
empty , following enabled. policy not working expected.
source code authorize method in gate facade:
public function authorize($ability, $arguments = []) { $result = $this->raw($ability, $arguments); if ($result instanceof response) { return $result; } return $result ? $this->allow() : $this->deny(); }
maybe not correct returing true or false in policy code expect result instance of response
return grant or deny access??
the problem putting policy inside commentpolicy , expected receive comment not post, moving postpolicy solved it.
Comments
Post a Comment