Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

digitalsuite.net's avatar

Restrict view of Resource

have the following problem:

Users (that are not admins) can view a resource (for example my resource documents) if they access it directly via a link.

I've modified the indexquery so that they cannnot see the resource on the index view but they also should get a 403 when they try to access it directly via an url.

I've already created a policy for my documents resource and I know that I somehow have to modify the view function.

  public function view(User $user, User $model){
    return true;
    // return canViewOwn($user); 
  }

I've tried creating a custom function in the documents model like so:

  public function canViewOwn($user){
    // This should test whether the current requested resource has the same user Id 
    //  as the currently logged in user

    if($user->id == auth()->user()->id) {
        return true;
    }
 }

My resource has a BelongsTo field which accepts the user id, but I dont know how to check for that in the resource model function.

In the end the user should only be able to see himself or the resources he created (which are linked through a belongsTo field).

I appreciate any help, thank you!

0 likes
4 replies
digitalsuite.net's avatar

@fylzero I'm not exactly sure if I understand how query scopes work. So do I modify every query for that resource and check if that user has access to view it?

How would that look like in practice, because I feel like I don't have access to the right variables....

If the current user is not an admin check if he is linked to the resource (I've added user_id as foreign key in the resource table and have admins add new resource entries while linking users to it)

Now I need to modify every query that checks whether current user is admin oder whether the current user is linked to that resource entry.

    protected static function booted()
    {
        static::addGlobalScope('age', function (Builder $builder) {
                   $current_user = auth()->user()->id;
   	           $builder->where('user_id', '=', $current_user);
        });
    }

How then do I apply the query scope function to the policy, because it seems they are defined in the model ?

fylzero's avatar
fylzero
Best Answer
Level 67

@digitalsuite.net Sorry, I probably didn't read the question close enough. I'm struggling to understand exactly what you want to do.

If you just want a 403 for the view page if the user isn't the authed user, just do...

public function view(User $user, User $model) {
    if ($user->id != auth()->user()->id) {
	abort(403, 'Nope, sorry.');
    }
}

Alternately you can move this code into authorize() method of a custom request. https://laravel.com/docs/8.x/validation#authorizing-form-requests

Please or to participate in this conversation.