Laravel Nova Restrict View of Resource

1.7k views Asked by At

I 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!

1

There are 1 answers

1
digitalsuite.net On BEST ANSWER

I just figured it out by myself, I was too confused while working in the UserPolicy:

It was just:

public function view(User $user, User $model){
    if($user->role === 'admin'){
        return true;
    } 
    return $model->id == $user->id;
}

And for any other Resource I used:

public function view(User $user, Document $document){
    if($user->role === 'admin'){
        return true;
     } 
     return $document->user_id == $user->id;
}