1

How can I use Laravel Policy for displaying all products for admin and editor but own product for vendor?

I have done the following in view and view-any

public function viewAny(User $user)
{
    return true;
}

public function view(User $user, Product $product)
{
    return $user->id === $product->vendor_id;
}

And in my blade template, I have done this:

@foreach($allProducts as $productLists)
   @can('view', $productLists)
      codes....
   @endcan
@endforeach
Gaurav
  • 149
  • 12

2 Answers2

1

you can't do that in Policy ...

Policy is meant to give you True or False so the current user can access the action in your controller ...

in your case, both admin and regular user can access your controller's action, so policy is not the place for that ...

you can do it in controller, something like:

  $currentUser = auth()->user();
        if ($currentUser->is_admin) {
            $values = DB::table('products')->get();
        } else {
            $values = DB::table('products')->where('owner_id', $currentUser->id)->get();
        }

now you can pass the $values to your view ....

OMR
  • 11,736
  • 5
  • 20
  • 35
  • I am struggling with laravel permission. I asked this question https://stackoverflow.com/questions/63130329/assigning-one-route-to-multiple-user-without-a-package-in-laravel and I was recommended to one from `Gate` and `Policy`. What will be the best to fix this? – Gaurav Jul 29 '20 at 07:27
  • yes, Gate and Policy are recommended when you want to restrict access to certain routes or controller's action, so user outside certain roles can't get in, but in your scenario, all the user roles can access, but with different results – OMR Jul 29 '20 at 08:14
1

Why don't you use policy filters?

Just keep the code below on the top of your ProductPolicy

public function before($user, $ability){
    if($user->role == 'admin' || $user->role == 'employee'){
        return true;
    }
}

You may want to visit laravel-documentation for more information.

  • Can you please help me with this https://stackoverflow.com/questions/63167346/authorizing-resource-controllers-in-laravel-post-does-not-work – Gaurav Jul 30 '20 at 07:17