Skip to content
Advertisement

Laravel: Prevent user access to specific resource

I have recourse api in my application. Currently there’s ‘domain.com/posts/:id’ route which returns specific post by id. All of users have access to it. But I want to allow user to see a post, if only he is author or editor of that post:

My post table has author_id and editor_id columns. Both columns have referenced to user table’s id.

Is it good practice to solve this problem with middlware/ (to create middlware for only one route?). Any suggestions ?

Advertisement

Answer

You can use authorization/policy or event Gates provided by laravel.

or just to keep it simple,

in your Post model

public function canView()
{
    return $this->author_id === auth()->id() || $this->editor_id === auth()->id();
}

in your controller

public function show(Post $post)
{
    //you already have the $post
    if(! $post->canView()) {
        // cannot view post
    }

   // can view post.
}

Following this way, you can use the same source of truth for authorization throughout your application easily as you’ll probably use eloquent’s instance throughout your application.

If your logic is more complex, reach for Laravel’s Policy

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement