iTranslated by AI
Laravel: Returning true in FormRequest's authorize Method is No Longer Required
Introduction
While looking at a class that inherits from FormRequest, I noticed that the authorize method was undefined. While thinking to myself, "I have to implement it to return true even if I'm not doing anything," I researched the code on GitHub and found that I didn't even need to return true. I'm going to write about that story here.
Environment
- PHP 8.2.3
- Laravel 10.7.1
What is the authorize method for?
Looking at the manual,
You may determine if the authenticated user actually has the authority to update a given resource.
*Note: This is a direct translation of the English manual.
It is a method that requires an implementation to return true if the user has the authority, and false if they do not.
However, if authorization checks are performed elsewhere, such as in middleware, you don't need to specifically do it in the FormRequest, so many articles suggest just returning true.
(Of course, there are also articles that show writing authorization check logic within the authorize method.)
I have been implementing it like this
I have been implementing it like the following, where I would return true without doing anything else.
use Illuminate\Foundation\Http\FormRequest;
class PostRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
//
];
}
Why you don't even need to return true
If we look at the actual location where the authorize method is used (the passesAuthorization method):
- If the
authorizemethod is defined, it executes theauthorizemethod and returns the result. - If the
authorizemethod is not defined, it returns true.
Since it is implemented this way, it means that if you aren't doing anything in the authorize method, you don't need to define it in the first place.
Since when did it become like this?
It seems to have changed in the following Pull Request:
Looking at the merged date:
Sep 3, 2018
This means that back on September 3, 2018—already five years ago (Laravel version 5.7)—it had already changed to an implementation that returns true by default. (I didn't know that.)
Summary
By chance, I looked into the implementation of the authorize method in the FormRequest class and found that while it was a necessary implementation in Laravel 5.6 and below, an implementation that "just returns true without doing anything" is no longer required in Laravel 5.7 and above (including Laravel 10.7.1 used for this investigation). That's all for this story!
Discussion