I want a middleware on my website for: People can edit their own posts but others posts. I tried this:
I get all posts that have the same post->user_id and user_id
$matches = Post::where('user_id', auth()->user()->id);
This gives back an array of posts that match the condition
Now what I want is to check if you are on a post that matches this condition, if the post->user_id and user_id do not match abort.
This is what I have, but you still can get on posts where the condition is NOT met.
if (!$matches){
abort(403);
}
return $next($request);
Abort when the criteria is not met and return the request when it is met
2
Answers
If you’re inside a post, I guess you will get the Post ID inside your request as well. Something like
http://127.0.0.1:5500/posts/1
Then you can get both Post and User ID. Use both values to determine whether the user has authorized the post or not.
Example:
Assume you have added the post ID URL Param as
post_id
Instead of using middleware why not use the
Policy
, and since you will edit apost
you can also use theForm Request
. I suggest you to useForm Request
then edit the
authorize()
and add the condition there.Okay lets say you are using
Route Model Binding
You can directly check if the user is the owner inside the
authorize()
. Assuming that you define the relationship between the post and userIt works if you will update the post but if just want to prevent the user from accessing the post they do not own. put this in your middleware.