Laravel 5 - Validation error on form doesn't r

2019-08-01 09:43发布

问题:

Entering data on a form that throws a validation error, doesn't re-input the user's previous input.

Controller

public function store(ClinicFormRequest $request)
    {

        $user = new \App\User;
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = Hash::make(str_random(10));
        $user->save();

        $user->user_id;

        $clinic = new \App\Clinic;
        $clinic->name = $request->clinicname;
        $clinic->telephone = $request->telephone;
        $clinic->save();

        $clinic->users()->attach(user_id);

        return Redirect::route('clinic.index')->with('message', 'Clinic created');

    }

Clinic Form Reqeust:

class ClinicFormRequest extends Request {

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
        'clinicname' => 'required',
        'name' => 'required',
        'email' => 'required|email|unique:users',
        'telephone' => 'required',
        'address' => 'required',
        'city' => 'required',
        'postcode' => 'required'
        ];
    }

}

Create.blade.php

@if($errors->has())
    <div class="alert alert-danger">
        @foreach($errors->all() as $error)
            <li>{{$error}}</li>
        @endforeach
    </div>
@endif

{!! Form::model(new App\Clinic, ['route' => ['clinic.store'], "class" => "form-horizontal"]) !!}

<fieldset>

    <!-- Form Name -->
    <legend>Add your clinic</legend>

    <!-- Text input-->
    <div class="form-group">
        <label class="col-md-4 control-label" for="clinicname">Clinic Name</label>  
        <div class="col-md-4">
            <input id="clinicname" name="clinicname" type="text" placeholder="" class="form-control input-md" required="">
            <span class="help-block">Your clinic's name</span>  
        </div>
    </div>

        <!-- Button -->
        <div class="form-group">
            <label class="col-md-4 control-label" for="register">Register</label>
            <div class="col-md-4">
                <button id="register" name="register" class="btn btn-success">Register your clinic</button>
            </div>
        </div>

    </fieldset>

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

Routes.php

Route::resource('clinic', 'ClinicController');

Any help would be greatly appreciated. Many thanks.

回答1:

You need to grab the value from the old input, like so:

<!-- Text input-->
<div class="form-group">
    <label class="col-md-4 control-label" for="clinicname">Clinic Name</label>  
    <div class="col-md-4">
        <input id="clinicname" name="clinicname" type="text" placeholder="" class="form-control input-md" required="" value="{{ old('clinicname') }}">
        <span class="help-block">Your clinic's name</span>  
    </div>
</div>

You should also consider to use the illuminate/html package, this automates the process of retrieving old input for you.