Validation error in Laravel array - $ errors are not populated after validation failure

I had a strange problem regarding validation in Laravel 5.2. I reviewed the following questions about StackOverflow, but none of them seem to apply to my case:

Laravel validation not showing errors

Laravel validation does not return an error

The thing is, I'm trying to check a field titlebefore moving an object Cardto the database. When I submit the form with an empty field title, as expected, it will not pass validation. However, the array is $errorsnot populated when the mentioned validations fail. Can someone explain where I am wrong in this code?

/////////////////////// CONTROLLER /////////////////////
public function create(Request $request)
{
    $this->validate($request, [
        'title' => 'required|min:10'
    ]);

    Card::create($request->all());
    return back();
}
///////////////////////// VIEW /////////////////////////
// Show errors, if any. (never gets triggered)
@if(count($errors))
    <ul>
        @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>
@endif
<form method="POST" action="/cards">
    {{ csrf_field() }}

    <div class="form-group">
        // The textarea does not get populated with the 'old' value as well
        <textarea class="form-control" name="title">{{ old('title') }}</textarea>
    </div>

    <div class="form-group">
        <button class="btn btn-primary" type="submit">Add Card</button>
    </div>
</form>
+4
3

Laravel 5.2.27 , . , , .

app/Http/RouteServiceProvider.php, :

protected function mapWebRoutes(Router $router)
{
    $router->group([
        'namespace' => $this->namespace, 'middleware' => 'web',
    ], function ($router) {
        require app_path('Http/routes.php');
    });
}

: https://github.com/laravel/laravel/blob/master/app/Providers/RouteServiceProvider.php#L53

, - . ( ) , , , .

Laravel, , : php artisan --version

+21

, if @if(count($errors) > 0)

0

In the controller, try adding an operator $validator->fails()and using it ->withErrors()return any errors to your template.

public function create(Request $request)
{
    $validator = Validator::make($request->all(), [
        'title' => 'required|min:10'
    ]);

    if ($validator->fails()) {
        return back()->withErrors($validator);
    }

    Card::create($request->all());
    return back();
}
0
source

All Articles