How to use policy in laravel livewire (return, it is not a trait)?

Viewed 76

I have category policy as below partial code.

class CategoryPolicy
{
    use HandlesAuthorization;

    public function view(User $user, Category $category)
    {
        return true;
    }
}

Then, I call from livewire component inside the mount method.

class Productcategorysetup extends Component
{
    use CategoryPolicy;
    public function mount()
    {
        $this->authorize('view',CategoryPolicy::class);  
    }
}

I got an error message

App\Http\Livewire\Generalsetting\Productcategorysetup cannot use App\Policies\CategoryPolicy - it is not a trait

Any advice or guidance on this would be greatly appreciated, Thanks.

1 Answers

To use authorization in Livewire, you need to import the AuthorizesRequests trait first, and use that in your class.

Secondly, the first argument to authorize() when using view, is the instance of a model - in your case, a category. But this sounds like you want to list categories, i.e. the "index" file - which means you want to check for viewAny (as view is for a specific resource). In that case, the second argument is the class-name of the model, rather than the instance of a model.

<?php 

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Models\Category;

class Productcategorysetup extends Component
{
    use AuthorizesRequests;

    public function mount()
    {
        $this->authorize('viewAny', Category::class);  
    }
}

Then in your policy,

class CategoryPolicy
{
    use HandlesAuthorization;

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

    public function view(User $user, Category $category)
    {
        return true;
    }
}
Related