2
votes

I've been struggling with this for a while now. Here's the code I've got.

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required|max:100'
    ]);
    if ($validator->fails()) {
        //do something
    }
}

The problem is that I get a FatalThrowableError right in my face with the following message:

Call to a member function parameter() on array

I can't find what I'm doing wrong. I'd appreciate some help here. And also, I've had this validation before which worked:

    $this->validate($request, [
        'name' => 'required|unique:developers|max:100'
    ]);

But the thing with this one is, I had no idea how to catch when the validation failed. Is it possible to catch the validation fail when using it this way?

Using version: "laravel/lumen-framework": "5.2.*"

1
What version of Lumen are you using? - Leon Vismer
"laravel/lumen-framework": "5.2.*" - Serellyn
My answer below was for 5.2 - Leon Vismer

1 Answers

4
votes

A FatalThrowableError exception is low level exception that is thrown typically by the symfony debug ErrorHandler. In lumen the queue worker, PhpEngine, console kernel and routing pipeline uses it as well.

Make sure of the following

  1. That you have copied .env.example to .env
  2. If you are using Facades, make sure that you enabled it inside bootstrap/app.php by uncommenting the line.

$app->withFacades();

Inside Lumen 5.2.8 either of the following would work.

The following will actually return a valid JSON object with the errors. You did not elaborate on your use case why that is not sufficient. What is nice with using the validate call like this is it actually returns a 422 http status code, which implies an unprocessed entity.

$app->get('/', function (Request $request) {
    $this->validate($request, [
        'name' => 'required'
    ]);
});

Using the facade works as well, albeit is returns a 200 status code.

$app->get('/', function (Request $request) {        
    $validator = Validator::make($request->only(['name']), [
        'name' => 'required'
    ]);

    if ($validator->fails()) {
        return ['error' => 'Something went wrong'];
    }
});

If you still do not come right with the Validator::make you can catch the default Validation exception using. It feels a little hacky.

$app->get('/', function (Request $request) {
    try {
        $this->validate($request, [
            'name' => 'required'
        ]);
    } catch (\Illuminate\Validation\ValidationException $e) {
        // do whatever else you need todo for your use case
        return ['error' => 'We caught the exception'];
    }
});