K
K
kulerezzz2017-05-06 13:30:01
Laravel
kulerezzz, 2017-05-06 13:30:01

How to configure error output after validation in Laravel?

When submitting the form....

@if (count($errors) > 0)
  <div class="alert alert-danger">
    <ul>
    @foreach ($errors->all() as $error)
      <li>{{ $error }}</li>
    @endforeach
    </ul>
  </div>
@endif
<form method="post" action="/regcontractor" name="regcompany">
<input type="hidden" name="formOfOwnership" value="company">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="panel panel-default company">
<table class="table">
<tr>
<td class="nameField">Email*</td>
<td class="field"><input class="form-control" type="text" name="email" value="{{ old('email') }}" required><small>Будет использоваться для входа</small></td>
</tr>
<tr>
<td class="nameField">Пароль*</td>
<td class="field"><input class="form-control" type="password" name="password" required></td>
</tr>
<tr>
<td class="nameField">Повторите пароль*</td>
<td class="field"><input class="form-control" type="password" name="reenterpassword" required></td>
</tr>
<tr>
<td></td>
<td>
<p><button type="submit" class="btn btn-default btn-lg"><span class="glyphicon glyphicon-ok"></span>&nbsp&nbspРегистрация</button></p></td>
</tr>
</table>
</div>
</form>

.... using the POST method, the router works ....
Route::post('/regcontractor', "[email protected]");

...calling controller...
namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Validator;

class Contractor extends Controller
{
    public function registration (Request $request)
    {

    	$title="Регистрация";

    	if ($request->isMethod('post')) 
    	{
    		$rules = 
    		[
    		
    			'email'=>'required|email',
    			'password'=>'required',
    			'reenterpassword'=>'required',

    		];

    		$this->validate($request, $rules);

    		return view('regcontractor',['title'=>$title]);

    	}

    }

FILE \app\Http\Kernel.php
namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}

$middleware contains the classes \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class
But errors from $errors are not shown in the view, as well as valid values ​​entered by the user ({{ old ('field name') }}). What could be the problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
kulerezzz, 2017-05-06
@kulerezzz

After a daily dance with tambourines and a call to five psychics, the solution was to put an id attribute in each input tag, the value of which is taken to compose the $errors object
Example:
Also, you still need to remove the loading of \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class in protected $middleware.
1397759758_747400265.jpg

P
Pavel, 2017-05-06
@Palych_tw

In the controller instead
of like this

$validator = Validator::make($request->all(), $rules]);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

Although the first option should also return both errors and the old input
. And where do you return the view, if the method is NOT POST, issue return view('regcontractor',['title'=>$title]); outside of the if condition, and add a get route to this page
And it's better to use the confirmed rule to confirm the password https://laravel.com/docs/5.4/validation#rule-confirmed
And which version of laravel? In 5.2, exactly all routes are given the web group by default. And you additionally recorded the start of the sessions globally in the intermediaries. Because of this, there may be glitches with sessions.

V
vism, 2017-05-06
@vism

this is how a redirect works after validation.

return redirect()->to($this->getRedirectUrl())
                        ->withInput($request->input())
                        ->withErrors($errors, $this->errorBag());

show the method and the view that displays the form.
Because what you posted works only according to the post

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question