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

sandaur's avatar

Authorize on form request or middleware

Hello,

i can't sleep thinking about whether the authorization for a resource should happen in a middleware or a form request.

i have these routes

poll/{id}/ poll/{id}/create poll/{id}/store poll/{id}/... (etc)

If i make a form request to use the authorize method i would have to make a form request for every route (because of the different inputs or lack of them in every route). This is the option that seems to be right but i if use a middleware i only have to create one that check if user owns poll with the given id, this makes more sense to me.

Any idea of what could be the way to go?

0 likes
4 replies
sandaur's avatar

Sorry, i totally meant to say authorization, check if someone owns a resource. Thanks for answering, i'll read that.

jlrdw's avatar

Authentication just means some user no matter what the level is now logged in.

But the form you were talking about if that particular user is not authorized then that form should not even show up for them.

Authorization is pretty complex and can go pretty deep.

Just my simple explanation and the way I see it.

Of course Authentication can be used alone for a system with just simple users and admin where as authorization just lets you start using roles permissions Etc.

crnkovic's avatar

I believe the OP meant to say should he perform authorization on specific endpoints by putting the can middleware on route declaration or by checking if the user is authorized to perform a request in authorize method of the form request object. Example:

Route::post('/resource/{resource}', 'action')->middleware('can:update-resource');

// or

class UpdateEndpoint extends FormRequest // inject this guy into the controller method
{
    public function authorize()
    {
        return Auth::user()->can('update-resource');
    }
}

I tend to use both. Why? Because of the reasons you said. If I use only form requests, there would need to be a request instance on each method of the controller, so I use middleware to keep it tidy. I also like to perform the check on Form Request on POST/PUT/DELETE requests just to make sure other developers reading the code can easily see what's going on.

BTW, you can use $this->authorize('update-resource', $resource) in your controllers, this is also a nice way to do that ;)

Please or to participate in this conversation.