2
\$\begingroup\$

This question is for Laravel 4 only, as the relevant parts are completely refactored in the upcoming Laravel 5.

I have written an helper function for validation, so I only have to put this in controllers:

public function postAdd()
{
    validate([
        'foo' => 'required',
        'bar' => 'required',
    ]);

    // process data...
}

I love it!

And here is the helper:

function validate($rules)
{
    $validator = Validator::make(Input::all(), $rules);

    if ($validator->fails())
    {
        $request = Request::instance();

        $response = Redirect::to(URL::previous())
            ->withInput()
            ->withErrors($validator);

        Session::save();
        $response->send();
        App::terminate($request, $response);
        exit;
    }
}

My concerns are mainly about the four last lines. The point is to immediately send the response, otherwise I have to return it from the helper, then handle the helper result (Response|null) in the controller (quite easy, but I want really thin controllers).

I did my best to return this response the more gracefully possible. Session data obviously has to be saved, and possible "finish" callbacks are triggered. But, looking at Application's run() and getStackedClient() method, I'm afraid of missing something.

So, am I missing something? Could this code be further improved?

\$\endgroup\$
1
  • \$\begingroup\$ Just as a reminder, Laravel 5 has simplified validation a lot and makes use of terminable middlewares, so you can simply do $this->validate(request(), $rules); in your controller. \$\endgroup\$ Commented Jun 26, 2017 at 2:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.