Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Void's avatar
Level 1

How to apply policy to a resource controller?

Hello. I have a basic resource controller and placing $this->authorize in every method isn't very good I think(maybe I am wrong). Also I have some custom methods(upload, develop) and I'd like to apply policy to those too. I found this method: $this->authorizeResource, but it always shows me "This action is unauthorized.". My model name is snake-cased(EmailList). Also my resource controller methods doesn't require model instance. Here is what I mean:

public function show($id) //--- As you see, no model instance here
    {
        $list = EmailList::find($id);
        //$this->authorize('view', $list);  //--- This works perfectly, by the way..
        return view('dispatch.lists.exact')->with('list', $list);
    }

Awaiting for your reply, thanks in advance!

0 likes
6 replies
tykus's avatar

Why can you not typehint the model? If you have a resource route with a hyphen, then the wildcard parameter will be snake_case...

...and in the controller, you can use camelCase for the typehinted variable name:

public function show(EmailList $emailList)
{
    return view('dispatch.lists.exact')->with('list', $emailList);
}
martinbean's avatar

@Void If you’re extending the base controller in Laravel, then you can use the authorizeResource() method:

class ArticleController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource(Article::class);
    }

    public function index()
    {
        //
    }

    public function create()
    {
        // Will call ArticlePolicy::create()
    }

    public function store()
    {
        // Will call ArticlePolicy::create()
    }

    public function show()
    {
        // Will call ArticlePolicy::view()
    }

    public function edit()
    {
        // Will call ArticlePolicy::update()
    }

    public function create()
    {
        // Will call ArticlePolicy::update()
    }

    public function create()
    {
        // Will call ArticlePolicy::delete()
    }
}
6 likes
Void's avatar
Level 1

Well, I did some changes to the code:

class EmailListsController extends Controller
{
    public function __construct()
        {
            $this->authorizeResource(EmailList::class);
        }
    ....
    public function show(EmailList $list)
        {
            return view('dispatch.lists.exact')->with('list', $list);
        }
    ....
}

But it always returns "This action is unauthorized.". Here is my view method in EmailListPolicy file:

....
    public function view(User $user, EmailList $list)
    {
        return $user->id === $list->user_id;
    }
....

And my route:

Route::resource('lists', 'Dispatch\EmailListsController');

What`s wrong?

Please or to participate in this conversation.