Kimmer
391
14
Laravel

Policies always results in "This action is unauthorized"

Posted 8 months ago by Kimmer

I followed the tutorial video, read the docs and searched the web. My code should work... yeah well... it doesn't and it's driving me mad.

I'm trying g to create a simple policy in Laravel.

In the controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Spot;

use App\Policies\SpotPolicy;

class spotController extends Controller
{
   public function delete($spot)
   {
       $this->authorize('delete', $spot);

       return 'Spot gets deleted';
   }

}

In the Policy file (app\Policies\SpotPolicy.php)

<?php

namespace App\Policies;

use App\User;
use App\Spot
use Illuminate\Auth\Access\HandlesAuthorization;

class SpotPolicy
{
    use HandlesAuthorization;

    public function delete(User $user, Spot $spot) 
    {
        dd('Stop here');
        
        return true;

    }
}

In the AuthServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        'App\Spot' => 'App\Policies\SpotPolicy'
    ];

    public function boot()
    {
        $this->registerPolicies();
    }
}

This always returns "Symfony \ Component \ HttpKernel \ Exception \ AccessDeniedHttpException This action is unauthorized.". The "delete" method in the SpotPolicy class is never reached.

Anyone... please?

Thanks

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.