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

luddinus's avatar

Authorize BEFORE validation rules (FormRequest)

Hi.

Imagine I have an "authorize" method of a FormRequest that depends on input.

class SomeRequest extends FormRequest {

   public function rules()
   {
      return [
         'user_id' => 'required'
      ];
   }

   public function authorize()
   {
      // this runs BEFORE the "rules" method, so "this->user_id" could be null
      // I would like to no to "execute" this if "user_id" is null (It has "required" rule)
      $user = User::find($this->user_id);

      // check something depending on the "user_id" method
      return true;
   }

}

Is there a better way to do this? Maybe validate in the controller method?

Thx.

0 likes
8 replies
ersinkandemir's avatar

Actually, authorization defines if it is okay for "authanticated user" to continue request life cycle. To implement a restriction logic on a user model getting from an input value, FormRequest authenticate function is not the place.

1 like
rodrigo.pedra's avatar
class SomeRequest extends FormRequest {

   public function rules()
   {
      return [
         'user_id' => 'required'
      ];
   }

   public function authorize()
   {
    if (empty($this->user_id)) { // no user id provided
            return false; // not authorized
        }

      $user = User::find($this->user_id);

      // check something depending on the "user_id" method
      return true;
   }

}

Authorization method on the FormRequest does not require an authenticated user. It is only suggested as an example in the docs to check something with the authenticated user:

... Within this method, you MAY check if the authenticated user...

source: https://laravel.com/docs/5.2/validation#form-request-validation

The parent FormRequest class will just check if the return value from this method is either true or false to continue the request or throw an exception.

lucio's avatar

Just ran into this same problem and thought of a similar workaround. Semantically speaking, however, this is a bad solution. It's going to reply back with HTTP 403 when the issue isn't really related to authorization.

Please or to participate in this conversation.