2016-05-11 2 views
4

Я пытаюсь применить валидацию в своей форме. Все работает хорошо, пока я не перейду в мой возврат $ this-> sendFailedLoginResponse ($ request) ;, где redirect() -> back() -> withErrors() не хранит ошибку в MessageBag (делая мои $ errors переменная пустая для моего представления).

laravel.blade.php

<!-- BEGIN LOGIN FORM --> 
     <form class="login-form" action="{{ url('/login') }}" method="post"> 
      {!! csrf_field() !!} 
      <h3 class="form-title font-green">Iniciar sesión</h3> 
       @if (count($errors) > 0) // Here is where i check and my $errors variable is empty 
        @foreach ($errors->all() as $error) 
         <div class="alert alert-danger"> 
          <button class="close" data-close="alert"></button> 
          <span>{{ $error }}</span> 
         </div> 
        @endforeach 
       @endif 
      <div class="form-group"> 
       <!--ie8, ie9 does not support html5 placeholder, so we just show field title for that--> 
       <label class="control-label visible-ie8 visible-ie9">Username</label> 
       <input class="form-control form-control-solid placeholder-no-fix" type="text" autocomplete="on" placeholder="Usuario" name="email" value="{{ (isset($email) ? $email : '') }}" /> </div> 
      <div class="form-group"> 
       <label class="control-label visible-ie8 visible-ie9">Password</label> 
       <input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="Contraseña" name="password" /> </div> 
      <div class="form-actions"> 
       <button type="submit" class="btn green uppercase">Iniciar sesión</button> 
      </div> 
     </form> 
     <!-- END LOGIN FORM --> 

AuthenticatesUsers.php

public function login(Request $request) 
{ 
    $this->validateLogin($request); 

    // If the class is using the ThrottlesLogins trait, we can automatically throttle 
    // the login attempts for this application. We'll key this by the username and 
    // the IP address of the client making these requests into this application. 
    $throttles = $this->isUsingThrottlesLoginsTrait(); 

    if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) { 
     $this->fireLockoutEvent($request); 

     return $this->sendLockoutResponse($request); 
    } 

    $credentials = $this->getCredentials($request); 

    if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) { 
     return $this->handleUserWasAuthenticated($request, $throttles); 
    } 

    // If the login attempt was unsuccessful we will increment the number of attempts 
    // to login and redirect the user back to the login form. Of course, when this 
    // user surpasses their maximum number of attempts they will get locked out. 
    if ($throttles && ! $lockedOut) { 
     $this->incrementLoginAttempts($request); 
    } 

    return $this->sendFailedLoginResponse($request); 
} 

/** 
* Validate the user login request. 
* 
* @param \Illuminate\Http\Request $request 
* @return void 
*/ 
protected function validateLogin(Request $request) 
{ 
    $this->validate($request, [ 
     $this->loginUsername() => 'required', 'password' => 'required', 
    ]); 
} 

/** 
* Get the failed login response instance. 
* 
* @param \Illuminate\Http\Request $request 
* @return \Illuminate\Http\Response 
*/ 
protected function sendFailedLoginResponse(Request $request) 
{ 
    return redirect()->back() 
     ->withInput($request->only($this->loginUsername(), 'remember')) 
     ->withErrors([ 
      $this->loginUsername() => $this->getFailedLoginMessage(), 
     ]); 
} 

/** 
* Get the failed login message. 
* 
* @return string 
*/ 
protected function getFailedLoginMessage() 
{ 
    return Lang::has('auth.failed') 
      ? Lang::get('auth.failed') 
      : 'These credentials do not match our records.'; 
} 
+0

Почему бы не попробовать '-> withErrors();' – haakym

+0

Потому что это настраиваемая ошибка. '-> withErrors ([ $ this-> loginUsername() => $ this-> getFailedLoginMessage(), ]); // он возвращает «Эти учетные данные не соответствуют нашим записям». ' –

+0

, если вы 'hardcode'' $ this-> loginUsername() 'с некоторой строкой, подобной' 'john'', что происходит? –

ответ

0

Здравствуйте Вы должны написать, как показано ниже перенаправления()

return redirect()->back()->with('status-keyword', 'error message'); 

и на переднем конце вы получите это сообщение с помощью

@if (session('error')) 
    <div class="alert alert-danger text-center msg" id="error"> 
    <strong>{{ session('error') }}</strong> 
    </div> 
@endif 

Я надеюсь, что это будет плодотворным для вас. Спасибо.

Смежные вопросы