【问题标题】:Laravel Redirect and Validation ErrorLaravel 重定向和验证错误
【发布时间】:2018-07-24 22:44:46
【问题描述】:

我创建了一个 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'
    ]);
}

【问题讨论】:

  • 我想我没有充分说明我的问题。我确实阅读了文档并让人们查看了我的代码(那些说我的代码看起来正确的人)。但是,它无法正常运行,这就是我寻求更多指导的原因。
  • 为什么不从小事做起,看看是否可行

标签: php laravel forms post


【解决方案1】:

请允许我采用一种不同的、更有条理的方法来组织您的后端代码。

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

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 中,当它到达控制器时,它们已经过验证,控制器只需要插入和输出预期的内容。

第一季度。你应该尝试一下吗?如果数据库有可能不是本地的或意外的,是的。

第二季度。我可以从控制器中抽象出更多代码吗?是的,在我看来,控制器应该只调用其他人(另一个类)来处理插入或更新操作并返回答案。

第三季度。这很漂亮,但是,我如何从输入中获取旧值?每当您使用 FormRequests 处理时,Laravel 都会返回一个 422 状态代码,以及一个名为 MessageBagError 的对象(现在不太感兴趣),但只要您的输入中有 old (并且 old('inputname') 等于名称将在此 FormRequest 中接收到的变量(顺便说一句),刀片将检测到它并填充它们。如果在另一种情况下,你想redirect()-&gt;back()-&gt;withInput();,你可以设置$requestwithInput($data)内部的数组,记住保留{{ old ('value') }},它应该由Laravel自动填充(因为{{}}对 laravel 的刀片是明确的,如果需要,您可以在其中编写 php 代码)。

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

第四季度。为什么我删除了 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

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 2017-10-20
    • 2015-08-13
    • 2015-11-14
    • 1970-01-01
    • 2015-11-11
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多