Actions always returning unauthorised

Viewed 35

I'm creating a simple e-commerce site as a personal project.

I have a products table that creates a relationship between each product listed by a user.

$table->foreign('owner_id')->references('id')->on('users')->onDelete('cascade');

The relationship works as expected, each product is assigned an owner_id that is equal to the user's ID who listed the product. I've checked the database in PHPMyAdmin and it's pointing to the correct user every time.

I generated a policy with artisan and pointed my model to it in order to use automatic route model binding

php artisan make:policy productsPolicy --model=products
public function canView(User $user, products $product)
{
    return $product->owner_id == $user->id;
}

My AuthServiceProvider points to the policy in question

protected $policies = [
    'App\Model' => 'App\Policies\productsPolicy',
];

I then reference the policy in my controller to only allow the creator to delete their listing

public function destroy(products $product)
{
    $this->authorize('canView', $product);
    $product->delete();

    return redirect('/');
}

No matter if I'm logged in as the user who created the project or not, the following exception is always thrown

AccessDeniedHttpException

1 Answers

You did not properly register your policy

protected $policies = [
    'App\Model' => 'App\Policies\productsPolicy', // 'App\Model' probably isn't a model
];

It should be

protected $policies = [
    'App\products' => 'App\Policies\productsPolicy',
];

or import the class

use App\Policies\productsPolicy;
use App\products;

protected $policies = [
    products::class => productsPolicy::class,
];
Related