Laravel重定向和验证错误

时间:2018-07-24 22:44:47

标签: php laravel forms post

我创建了Laravel表单,但是遇到了一些问题。当表单提交的信息不符合要求时,我希望表单重定向并在表单上(在输入下方)显示验证错误。此外,当表单重定向时,我希望它保留以前的(旧)值。请给我一些指导。

问题:

当我输入与验证要求不符的信息时,表单将刷新,但不会显示任何验证错误,并且不会保留任何旧的输入。 (我只是得到了一个全新的表单,没有任何旧输入,也没有验证错误。)

HTML:

 <form role="form" action="" method="post" class="registration-form">

                            <fieldset>
                                {{ csrf_field() }}

                                <div class="form-top">

                                    <div class="form-top-left">
                                        <h3>Insight Contributor Account Info</h3>

                                    </div>
                                    <div class="form-top-right">

                                    </div>
                                </div>

                                <div class="form-bottom" style="height: 400px">
                                    <!--Name-->
                                    <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">

                                        <div class="col-md-8 col-md-offset-2">

                                            <input id="name" type="text" class="form-control" name="name"
                                                   placeholder="Full Name (e.g. John Doe)" value="{{ old('name') }}">
                                            <br>

                                            @if ($errors->has('name'))
                                                <span class="help-block">
                                                    <strong>{{ $errors->first('name') }}</strong>
                                                <h3> name is required</h3>
                                            </span>
                                            @endif
                                        </div>
                                    </div>
                                    <!--Email-->
                                    <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">

                                        <div class="col-md-8 col-md-offset-2">
                                            <input id="email" type="email" class="form-control" name="email"
                                                   placeholder="Primary Email Address (e.g.Jdoe@gmail.com)"
                                                   value="{{ old('email') }}"><br>
                                            @if ($errors->has('email'))
                                                <span class="help-block">
                                                    <strong>{{ $errors->first('email') }}</strong>
                                                </span>
                                            @endif
                                        </div>
                                    </div>
                                    <!--Password-->
                                    <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                                        <!-- <label for="password" class="col-md-4 control-label">Password</label>-->
                                        <div class="col-md-8 col-md-offset-2">
                                            <input id="password" type="password" class="form-control"
                                                   placeholder="Password (at least 6 character)" name="password"><br>
                                            @if ($errors->has('password'))
                                                <span class="help-block">
                                                    <strong>{{ $errors->first('password') }}</strong>
                                                </span>
                                            @endif
                                        </div>
                                    </div>
                                    <!--PasswordConfirm-->
                                    <div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
                                        <div class="col-md-8 col-md-offset-2">
                                            <input id="password-confirm" type="password" class="form-control"
                                                   placeholder="Confirm Password" name="password_confirmation"><br>

                                            @if ($errors->has('password_confirmation'))
                                                <span class="help-block">
                                                    <strong>{{ $errors->first('password_confirmation') }}</strong>
                                                    <h3> password mismatch</h3>
                                                </span>
                                            @endif
                                        </div>
                                    </div>
                                </div>

                                <div class="form-top" style="margin-top: 10px">

                                    <div class="form-top-left">
                                        <h3>Professional Information</h3>
                                    </div>

                                </div>

                                <div class="form-bottom" style="height: 460px">
                                    <!--Primary Industry(single value)-->
                                    <div class="form-group{{ $errors->has('industry') ? ' has-error' : '' }}">

                                        <div class="col-md-8 col-md-offset-2"><br>
                                            <select class="form-control selectpicker" name="industry" id="industry">
                                                <option selected disabled>Primary Industry</option>
                                                <option>Art</option>
                                                <option>Business</option>
                                                <option>Law</option>
                                                <option>Media</option>
                                                <option>Medicine</option>
                                                <option>Education</option>
                                                <option>Technology</option>
                                                <option> Science</option>
                                                <option>Service</option>
                                                <option>Other</option>
                                            </select>


                                            @if ($errors->has('industry'))
                                                <span class="help-block">
                                                <strong>{{ $errors->first('industry') }}</strong>
                                                </span>
                                            @endif
                                        </div>
                                    </div>


                                    <!--Primary Job Function (single value)-->
                                    <div class="form-group{{ $errors->has('job_function') ? ' has-error' : '' }}">

                                        <div class="col-md-8 col-md-offset-2"><br>
                                            <select class="form-control selectpicker" name="job_function"
                                                    id="job_function">
                                                <option selected disabled>Primary Job Function</option>
                                                @foreach($professions as $profession)
                                                    <option @if ($profession->id == old('job_function_id')) selected
                                                            @endif value="{{ $profession->id }}">{{ $profession->name }}</option>
                                                @endforeach
                                            </select>

                                            @if ($errors->has('job_function'))
                                                <span class="help-block">
                                                <strong>{{ $errors->first('job_function') }}</strong>
                                                </span>@endif



                                        </div>
                                    </div>

                                    <!--Add relative experience (multi tag)-->
                                    <div id="tags" class="form-group" style="margin-top: 30px">

                                        <div class="col-md-8 col-md-offset-2"><br>


                                            <select id="test" style="width: 100%;margin-left: 10%;" name="tags[]"
                                                    multiple>

                                                <option value="root" disabled="disabled">Tags</option>
                                                <option value="level11" parent="root" disabled="disabled">Subjects
                                                </option>
                                                <option value="level12" parent="root" disabled="disabled">Grades
                                                </option>
                                                <option value="level13" parent="root" disabled="disabled">Relationship
                                                    Management
                                                </option>
                                                <option value="level14" parent="root" disabled="disabled">Classroom
                                                    Management & Design
                                                </option>
                                                <option value="level15" parent="root" disabled="disabled">Curricula &
                                                    Resources
                                                </option>
                                                <option value="level16" parent="root" disabled="disabled">Professional
                                                    Growth & Career Management
                                                </option>
                                                <option value="level17" parent="root" disabled="disabled">More</option>
                                                @foreach($tags as $tag)

                                                    @if($tag->category =='Subjects')
                                                        <option value='{{ $tag->id }}'
                                                                parent="level11"> {{$tag->name}}</option>
                                                    @endif
                                                    @if($tag->category =='Grades')
                                                        <option value='{{ $tag->id }}'
                                                                parent="level12"> {{$tag->name}}</option>
                                                    @endif
                                                    @if($tag->category =='Relationship Management')
                                                        <option value='{{ $tag->id }}'
                                                                parent="level13"> {{$tag->name}}</option>
                                                    @endif
                                                    @if($tag->category =='Classroom Management & Design')
                                                        <option value='{{ $tag->id }}'
                                                                parent="level14"> {{$tag->name}}</option>
                                                    @endif
                                                    @if($tag->category =='Curricula & Resources')
                                                        <option value='{{ $tag->id }}'
                                                                parent="level15"> {{$tag->name}}</option>
                                                    @endif
                                                    @if($tag->category =='Professional Growth & Career Management')
                                                        <option value='{{ $tag->id }}'
                                                                parent="level16"> {{$tag->name}}</option>
                                                    @endif
                                                    @if($tag->category =='More')
                                                        <option value='{{ $tag->id }}'
                                                                parent="level17"> {{$tag->name}}</option>
                                                    @endif
                                                @endforeach

                                            </select>
                                            @if ($errors->has('tags'))
                                                <span class="help-block">
                                        <strong>{{ $errors->first('tags') }}</strong>
                                        </span>
                                            @endif
                                        </div>
                                    </div>


                                    <!--Bio-->
                                    <div class="form-group{{ $errors->has('bio') ? ' has-error' : '' }}">
                                        <!--  <label for="bio" class="col-md-4 control-label">Short Bio</label> -->

                                        <div class="col-md-8 col-md-offset-2"><br>
                                        <textarea id="bio" class="form-control" placeholder="Brief profile bio"
                                                  name="bio">{{ old(nl2br('bio')) }}</textarea><br>


                                            @if ($errors->has('bio'))
                                                <span class="help-block">
                                                    <strong>{{ $errors->first('bio') }}</strong>

                                                </span>
                                            @endif
                                        </div>
                                    </div>
                                </div>

                                <div class="form-top" style="margin-top: 10px">

                                    <div class="form-top-left">
                                        <h3> Agreements </h3>
                                    </div>

                                    <div class="form-top-right">
                                    </div>
                                </div>

                                <div class="form-bottom">

                                    <!--Terms-->
                                    <h2 class="section-heading">Cypress Community Principles</h2>
                                    <p class="lead">
                                        <br>
                                        Teachers value each other for their expertise.<br><br>

                                        Teachers believe in the power of collaboration and will work together to engage
                                        in
                                        open and honest dialogue, provide guidance and mentorship, and create content
                                        that
                                        supports growth and success for fellow teachers.<br><br>

                                        Teachers will respect each other and be mindful of what they post. We encourage,
                                        open and honest communication, a diversity of perspectives, and thoughtful
                                        disagreement. Harassment, disrespect, and inappropriate content are not
                                        tolerated.<br><br>

                                        Teachers will actively engage in fostering a positive community of learning and
                                        growth.<br><br>

                                        Teachers are the most significant influence on a student’s academic achievement
                                        and
                                        will support fellow teachers as agents of change and innovators of
                                        education.<br><br>
                                    </p>

                                    <form action="#"
                                          onsubmit="
                                      if(document.getElementById('agree').checked) {
                                      return true;

                                      } else
                                      { alert('Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy');
                                      return false;
                                      }">
                                        <input type="checkbox" name="checkbox" value=0 id="agree"/> I have read and
                                        agree to
                                        the Community Principle,
                                        <a href="/terms" style="color: #5dc19f">Terms
                                            and Conditions
                                        </a> and
                                        <a href="/privacypolicy" style="color: #5dc19f">Privacy
                                            Policy</a><br><br>

                                    </form>

                                    <!--Signup botton-->
                                    <button type="submit" id="submit" class="btn btn-default"
                                            style="background-color: #a5d5a7">
                                        <i class="fa fa-btn fa-user"></i> Sign me up!
                                    </button>

                                    <button type="button" class="btn btn-default" style="background-color: #a5d5a7">
                                        <a class="btn btn-link" href="{{ url('/') }}" style="color: whitesmoke">
                                            Cancel </a>
                                    </button>


                                </div>
                            </fieldset>

                        </form>

PHP:

public function register(Request $request)
{
    $tags = Tag::all();
    $professions = Profession::all();

    if ($request->isMethod('post')) {

        $validator = $this->validateRegister($request->input());
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput(); //TODO

        }
        $user = Iuser::create([
            'name' => $request['name'],
            'email' => $request['email'],
            'password' => bcrypt($request['password']),
            'bio' => $request['bio'],
            'industry' => $request['industry'],
            'confirmation_code' => str_random(30),
            'job_function' => $request['job_function'],
        ]);
        $user ->tags()->sync($request['tags']);

        #event(new NewUserWasRegistered($user));


        if($user->save()){
            return redirect('/insight/login')->with('success', 'Welcome to Cypress!');
        }else{
            return back()->with('error', 'Register failed!')->withInput();
        }
    }
    $datas = array('tags' => $tags, 'professions'=>$professions);
    #return $user;
    return view('iauth.register')->with($datas);
}



protected function validateRegister(array $data)
{
    return Validator::make($data, [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6|confirmed',
        'password_confirmation' => 'required|min:6',
        'bio' => 'required',
        'industry' => 'required|string',
        'job_function' => 'required|string',
    ], [
        'required' => ':attribute is required',

        'min' => ':attribute is too short',
        'confirmed' => 'different passwords',
        'unique' => 'This email exits',
        'max' => ':attribute is too long'
    ]);
}

1 个答案:

答案 0 :(得分:0)

允许我采用其他更结构化的方法来组织后端代码。

首先让我们将验证器函数安排到一个类中

  

https://laravel.com/docs/5.6/validation#creating-form-requests

写下:php artisan make:request RegisterUser

  

https://laravel.com/docs/5.6/validation

这将在App\Http\Requests下创建类似的内容:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class RegisterUser extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $content = [
          'name' => 'required|max:255',
          'email' => 'required|email|max:255|unique:users',
          'password' => 'required|confirmed|min:6', //confirmed means it will receive password_confirmed aswell
          'bio' => 'required',
          'industry' => 'required|string',
          'job_function' => 'required|string'
        ];
        return $content;
    }
}

在您的控制器上,您将:

use App\Http\Requests\RegisterUser;
.
.
.
public function register(RegisterUser $request)
{    
    //fetch the validated data to this $data variable, that is now an array
    $data = $request->validated(); //Or all, whatever you'd like
    //add this variable to the array
    $data['confirmation_code'] = str_random(30);
    //since all inputs have the same name as your table, you can just give it to him and he'll insert
    //Whatever is in your $fillable array in Iuser, it will be filled and only that. 
    //If you send more data than needed, theres no worries as he will only insert what is in that array.
    $user = Iuser::create(data);
    //? dunno but sure
    $user ->tags()->sync($request['tags']);

    //Something about some event
    #event(new NewUserWasRegistered($user));

    return redirect('/insight/login')->with('success', 'Welcome to Cypress!');
}

现在,为什么我删除了这么多代码:

现在,您已经将逻辑结构分开了,而不是将所有内容放在一个位置(控制器中仍然有一些不同的操作)。对后端的请求的验证在FormRequests中进行,并在到达控制器时进行验证,并且Controller只需插入并输出期望的内容即可。

Q1。你应该试试看吗?如果数据库不是本地数据库或出现意外情况,则可以。

Q2。我可以从控制器中提取更多代码吗?是的,我认为您应该,控制器应该只呼叫其他人(另一个类)来处理插入或更新操作并返回答案。

Q3。这很漂亮,但是,如何从输入中获取旧值?每当您使用FormRequests处理时,Laravel都会返回422状态代码,以及一个称为MessageBagError的对象(目前不怎么吸引人),但前提是您输入的内容已旧(且old('inputname')等于名称)在此FormRequest中将要接收的变量中(即按您的规则设置),刀片将对其进行检测并填充它们。如果在另一种情况下,您想要redirect()->back()->withInput();,则只需设置$requestwithInput($data)内的数组,并记住保留{{ old ('value') }},它应该自动填充由Laravel提供(因为{{}}对于laravel的刀片来说是显式的,并允许您在需要时在其中编写php代码)。

  

https://laravel.com/docs/5.6/requests#old-input

Q4。为什么要删除HTTPPost验证?因为您可以在route folder上建立路线和httpverbs(例如

Route::get('home',function(){
  return view('home');
})->name("home");

Route::post('register', "RegisterController@register");
//Meaning, anyone who attempts to access host/register by not using HTTPost will receive a 405 Status code (Method not allowed)
  

https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html