Quoting the Laravel documentation:
By default, Laravel's base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP request with a variety of powerful validation rules
It's true, reading the code, App\Http\Controllers\Controller
actually uses ValidatesRequests
trait. And ValidatesRequests
has a validate
method.
What is really strange for me is that everywhere else in the documentation, the validate
method is called on $request
object. And it works this way. I can validate a form with this code:
public function store()
{
$attributes = request()->validate([
'name' => 'required|string|max:255',
]);
// ...
}
But I don't see any presence of a validate method on the Request class. Just a strange comment line at the beginning of the file:
/**
* @method array validate(array $rules, array $messages = [], array $customAttributes = [])
*/
So there are two things:
$request
object.And my actual question is:
Is the initial quote I pasted from the documentation still true if I use the validate
method through $request
object? If so, how does it works?
That "strange comment" was removed a couple days ago.
I believe Request
gets its validate
function from the Request::macro('validate', ...)
call in FoundationServiceProvider.php. See this article for more on macros.