Home > Mobile >  Laravel middleware with a where function
Laravel middleware with a where function

Time:10-31

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

CodePudding user response:

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

$match = Post::where('user_id', auth()->user()->id)->where('id', $request->route('post_id'));

if (!$match){
   abort(403);
}


return $next($request);

CodePudding user response:

Instead of using middleware why not use the Policy, and since you will edit a post you can also use the Form Request. I suggest you to use Form Request then edit the authorize() and add the condition there.

Okay lets say you are using Route Model Binding

//route

Route::put('/post/{post}', ['PostController','update']);

//controller

public function update(Post $post, UpdatePostRequest $request) {...}

You can directly check if the user is the owner inside the authorize(). Assuming that you define the relationship between the post and user

// app\Models\User.php
public function posts() : HasMany {...}

// app\Models\Post.php
public function user() : BelongsTo {...}
//request
class UpdatePostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        //true if the Auth::user() own the post. otherwise false.
        return $this->post->user()->is(Auth::user());
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            // Your validation rules
        ];
    }

It 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.

if(! $request->post->user()->is(Auth::user())) {
    abort(403);
}

return $next($request);
  • Related