Validation of fields in Lumen 5.5

0

In version 5.2 of Lumen the following validation in Controller is working:

$this->validate($request, [
        'nome' => 'required',
        'email' => 'required|email',
        'cpf' => 'required',
    ]);

Same as the following View:

@if (count($errors) > 0) {
    <div>
        <ul>
            @foreach($errors->all() as $error){
                    echo("<li>". $error . "</li>");
                 }
            @endforeach     
        </ul>
    </div>
@endif

It happens that in version 5.5 of Lumen is not working.

  

The following error is displayed: 1/1) ErrorException Undefined variable: errors in cadastroPessoas.php (line 8) at Application-> Laravel \ Lumen \ Concerns {closure} (8, 'Undefined variable: errors' C: \ wamp64 \ www \ blog \ resources \ views \ domainname.php ', 8, array (' __ path '=>' C: \ wamp64 \ www \ blog \ resources \ '__enable' => object (Factory), 'app' => object (Application)), 'obLevel' => 1, '__env' => object (Factory) 'app' = > object (Application)) in cadastroPessoas.php (line 8) at include ('C: \ wamp64 \ www \ blog \ resources \ views \ cadastroPe ssoas.php

    
asked by anonymous 16.10.2017 / 16:09

1 answer

1

Not working is very ambiguous, probably 500 internal error server should be running (if DEBUG is off) or it is displaying an exception.

It seems to me that it is a series of typos :

It has a { that is not necessary, in "Views" this is not used:

@if (count($errors) > 0) { <--- ISTO
...
    @foreach($errors->all() as $error){ <--- ISTO

and } :

    echo("<li>". $error . "</li>");
 } <--- ISTO

and maybe echo also does not work (it does not make sense, even if it works, use echo, after all the rest did not need it)

It should look like this:

@if (count($errors) > 0)
    <div>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach     
        </ul>
    </div>
@endif

Make the examples always according to the documentation: link

  

Note: I do not know if $errors works with count() , but in the example it is with ->any() , so if the script still fails,

@if ($errors->any())
    <div>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach     
        </ul>
    </div>
@endif

Important note about $ errors in Laravel / Lumen views

To make $errors available, add the Illuminate\View\Middleware\ShareErrorsFromSession to the middleware, then go to bootstrap/app.php and add this:

$app->middleware([
   Illuminate\View\Middleware\ShareErrorsFromSession::class
]);

So the $errors will be "global", if you have not added Lumen will trigger the error:

  

ErrorException Undefined variable: errors

    
16.10.2017 / 16:25