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

Th3apprenTis's avatar

Call a form request validation from middleware

I use form request to validate data from forms($request->url attribute).However in one of my middleware for another route , i want to execute validation again.If i set a value for $request->url , how can i call the form request again.I want to eliminate code duplication here as the form request already contain the form validation that i need

0 likes
6 replies
Talinon's avatar

@th3apprentis

If I understand correctly, you just need to make a FormRequest class to handle your validation:

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

Place all your validation into a FormRequest class, and then for each route you require it, just typehint it within the corresponding controller's method. The validation will automatically be ran.

public method store(\App\Http\Requests\MyRequest $request)
{

    // This code will not execute if validation fails

}
kapilvermasgnr's avatar

I think he is asking about to validate the request in the middleware itself.

Commander's avatar

In middleware you can try this

if ($request->url) {
    // do stuff
} 

Or this could also work, since $request is an instance of \Illuminate\Http\Request

$request->validate([
    "url" => "validation rules here" 
]);
matfish2's avatar

This has worked for me on Laravel 8:

 $request = MyFormRequest::createFromGlobals();
 $request->setContainer(app(Container::class));
 $request->setRedirector(app(Redirector::class));
 $request->validateResolved();
martinbean's avatar

People should not be calling form requests from middleware. Completely defeats the purpose of both middleware and form requests.

Parog's avatar

@martinbean While I agree with you, the response is not constructive.

Correct me if I'm wrong; FormRequest should be used when validating input data ( Whether it's user input or otherwise ) and Middleware for other things such as headers or other validation logic that touch more than a single type of resource. ( IE: Covering an entire route group for an external API call with a JWT token third-party scope validation )

Please or to participate in this conversation.