Gaurav
Gaurav

Reputation: 149

Display own post only and all posts for admin with laravel policy

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

Upvotes: 1

Views: 1793

Answers (2)

Alisha Lamichhane
Alisha Lamichhane

Reputation: 514

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.

Upvotes: 1

OMR
OMR

Reputation: 12218

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 ....

Upvotes: 1

Related Questions