How can I redirect with old input in Laravel?

℡╲_俬逩灬. 提交于 2020-06-25 07:46:33

问题


I have a login modal. When the user log-in fail the authentication, I want to redirect back to this modal with :

  • error message(s)
  • and old input(s).

enter image description here


Controller

// if Auth Fail 
return Redirect::to('/')
                ->with('error','Username/Password Wrong')
                ->withInput(Request::except('password'))
                ->withErrors($validator);

Form

{!! Form::open(array('url' => '/', 'class' => 'login-form')) !!}

  <div class="form-group">
    <label for="username">Username</label>
    <input type="text" class="form-control"  id="username" name="username" placeholder="Enter Username" required>
  </div>
  <div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" id="password" name="password" placeholder="Enter Password" required>
  </div>
  <button type="submit" class="btn btn-primary">Login</button>

{!! Form::close() !!}

As you can see as part of my image, the error message seem to display, but the old input of username doesn't seem to populate.

Can someone please correct me ? Did I forget to do anything ? What is the most efficient way in Laravel to accomplish something like this ?


回答1:


You can access the last inputs like so:

$username = Request::old('username');

As pointed at by @Arian Acosta you may simply do

<input type="text" ... value="{{ old('username') }}" ... >.

As described in the docs it is more convenient in a blade view.


There are several possibilties in the controller:

Instead of ->withInput(Request::except('password'))

do:

a) Input::flash();

or:

b) Input::flashExcept('password');

and redirect to the view with:

a) ->withInput(Input::except('password'));

resp. with:

b) ->withInput();

The docs about Old Input for further reading...




回答2:


You are missing the value on your input element...

value="{{ Input::get ('username', '') }}"



回答3:


For my project, I needed another way:

Shove a GET request in the validation return to fetch some previous data:

   // if the validator fails, redirect back to the form
    if ($validator->fails()) {
        //let's send some data back (Orlando,Florida):
        return Redirect::to('auth/register?city=Orlando&State=Florida')
            ->withErrors($validator)


    }else{
     //validation success
    }


来源:https://stackoverflow.com/questions/30002608/how-can-i-redirect-with-old-input-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!