FatMooseHenry's avatar

Custom Requests

Hi I'm using lumen 5.5 and I'm trying to put my requests into custom request objects, so that I would be able to do a controller method as:

public function login(LoginRequest $r) instead of:

public function login(Request $r){ $this->validate(...) $r->all() ... }

I was hoping that I would be able to get the login method executed only when the data was validated and populated into the LoginRequest object

I've found this: https://laracasts.com/discuss/channels/laravel/laravel-5-custom-request-not-working But I cant figure out which Request object that I should extend to overwrite 'rules' method

An alternative suggestion is here, but I can't find the FormRequests which I guess is a part of Laravel and not lumen:

https://8thlight.com/blog/mike-knepper/2016/09/26/laravel-controllers-clean-with-form-requests.html

The question is... if I have a class called LoginRequest with a 'email' and 'password' property, is there any way I can extend a request, put validation logic into it, and getting the fields populated with data before reaching the login method of the controller? (I'm a bit new in the world of lumen and laravel)

And which Request object is it that I should extend? Thanks :)

0 likes
1 reply
KrzysztofNiepokojczycki's avatar

There are probably more workarounds but what I'd do in that case is create a custom validator, that hold rules and messages. For instance:

class UserValidator
{
    /**
     * @param array $data
     * @return array of errors
     */
    public function validate(array $data)
    {
        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($data, $this->rules(), $this->messages());

        return $validator->errors()->toArray();
    }

    /**
     * @return array
     */
    protected function rules()
    {
        return [
            // rules
        ];
    }

    /**
     * @return array
     */
    protected function messages()
    {
        return [
            // messages
        ];
    }
}

You then can inject this validator to controller and ask it for errors


    public function create(UserValidator $validator, Request $request)
    {
        $errors = $validator->validate($request->all());

        if (sizeof($errors)) {
            // validation failed, do something
        }
        
        // do something else
    }

Actually for more reusable code you can extract this part to a superclass so each custom validator only holds data about rules and messages or so.

 /**
     * @param array $data
     * @return array of errors
     */
    public function validate(array $data)
    {
        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($data, $this->rules(), $this->messages());

        return $validator->errors()->toArray();
    }
2 likes

Please or to participate in this conversation.