imJohnBon's avatar

FormRequests in Lumen

I'm trying to figure out how to create a custom Request class to handle request validation in Lumen. In Laravel, you can do it easily by extending the FormRequest class, but Lumen does not include illuminate/foundation which is what powers that.

There are some references to this functionality online:

https://github.com/laravel/lumen-framework/issues/124 https://github.com/dingo/api/issues/717

And there's even a Laracasts thread about it:

https://laracasts.com/discuss/channels/lumen/how-can-i-use-illuminatefoundationhttpformrequest-on-lumen-micro-framework?page=0

However the solutions in there all seem a bit hacky.

In that first GitHub like, GrahamCampbell said "You can still set them up with some ioc bindings though.". Has anyone figured this out and have an example of how to implement it?

0 likes
3 replies
spekkionu's avatar

Functionality like this is why Laravel and Lumen are separate projects.

If you find yourself pulling in a bunch of Laravel functionality into Lumen why are you using Lumen in the first place?

Rather than pulling in the entire illuminate/foundation you could probably just copy the FormRequest class into your project.

You would then need to catch Illuminate\Contracts\Validation\ValidationException to flash the error messages and the old input data into the session (so you'll need to pull in the session package as well) and redirect back to the page with the form.

imJohnBon's avatar

@spekkionu

Thanks for the reply.

I'm not trying to pull in a bunch of Laravel functionality into Lumen though, literally just Form Requests because they're a great way to keep controllers slim and separate concerns.

What you suggested is exactly what the old thread I linked to suggests as well. Unfortunately, as you mentioned, it seems that functionality has roots that go a bit deeper than what is necessary for an API (like sessions, flash data, redirects, etc).

I guess, at a basic level, I wish Lumen either included a slimmed down version of Form Requests or, at least, it'd be great if the documentation explained how to do it on your own (or a third party blog post or something). Currently the only thing that can be found around implementing it yourself is a one-off github comment that says "you can still set them up with some ioc bindings though" with no further explanation despite 2 subsequent comments in that thread which express the same question I have.

If I ever figure it out I'll come back to this thread and write out an explanation. Until then, I suppose the only way is to use the $this->validate() method directly in controller methods.

1 like

Please or to participate in this conversation.