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?
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.
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...
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.
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.