In my laravel/nova app, I need to set something like that: users must see own posts, can't able to see others posts. For example:
| id | name | user_id |
|----|-------------|---------|
| 1 | POST1 | 1 |
| 2 | POST2 | 1 |
| 3 | POST3 | 2 |
In this situation if we are the id=1 user, just see first two posts. This is easy, I read the doc and made it with this.
In the related model I did this:
public static function indexQuery(NovaRequest $request, $query)
{
if(auth()->user()->hasRole('admin'))
{
return $query;
}
if(!auth()->user()->hasRole('admin'))
{
return $query->where('user_id', auth()->user()->id);
}
}
But I still see this like that: ..../resources/posts/3
I must unable to see and I need get 403 page. Where should I put this statement? I was created policy earlier. In posts policy,
public function view(User $user, Company $company)
{
return auth()->user()->hasRole(['supervisor', 'admin']);
}
This doesn't solve the issue too. These are what I tried, its just not displaying. But I need to abort 403 or smt.
Can anybody help me i'll glad so much. Thanks in advance.
Current policy condition auth()->user()->hasRole(['supervisor', 'admin'])
, checks only whether authenticated user has given roles. It doesn't check for own post.
Update your post policy condition as below. Also note the second parameter is instance of Post
not Company
public function view(User $user, Post $post)
{
return $post->user_id == $auth()->user()->id;
}