0

In my Laravel 5.1 application, I have a controller that serves as a RESTful API. Many methods of this controller have a following piece of code:

foreach (['email', 'password', 'firstName', 'lastName'] as $parameter) {
    if (!$this->request->has($parameter)) {
        throw new InputException(400, $parameter, 'Missing ' . $parameter . ' parameter.');
    }
}

I know it's not the greatest idea to repeat the same piece of code (with different array contents). Instead, I'm looking for some elegant way to achieve the same thing.

I thought about middleware with parameters, something like this in the routes.php:

'middleware' => 'parameters:email,password,firstName,lastName'

Currently I'm using implicit controllers though, so my methods are not mentioned in routes.php file.

What is the most flexible and elegant way to implement this functionality without repeating myself?

jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107
Robo Robok
  • 21,132
  • 17
  • 68
  • 126

2 Answers2

1

Laravel's validator is what you need.

If you have a controller class, you can just add the following in the action method:

 $this->validate($this->request, [
    'email' => 'required|email',
    'password' => 'required',
    'firstname' => 'required',
    'lastname' => 'required',
]);

This will validate the incoming request and throw HttpResponseException if validation rules are not met.

Laravel's Validator is a powerful tool - you can read more about it here: http://laravel.com/docs/5.1/validation

jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107
0

I think, Middleware would be the best option. Middlewares are amazing. Just create a middleware using php artisan make:middleware SomeMiddlewareName

and put this code in its handle function

public function handle($request, Closure $next)
{

    $data = array(
        'email' => $request->input('email'),
        'password' => $request->input('password'),
        'firstname' => $request->input('firstname'),
        'lastname' => $request->input('lastname'),
    );

    //Delete array fields that Have null or empty values
    $data = array_filter($data);

    if (sizeof($data) == 4) {
            //Send the user to the required controller
            return $next($request);
    } else {
        //Else, throw whatever error you want to throw
        throw new InputException("Enter all required parameters");
    }
}

I think it will work for you.

Parthapratim Neog
  • 4,352
  • 6
  • 43
  • 79