Laravel 5.2 表单验证请求无法正常工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37163837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:46:29  来源:igfitidea点击:

Laravel 5.2 form validation request not working properly

phpvalidationlaravelrequest

提问by emurmotol

When I hit submit button nothing happens its just refreshing the page.

当我点击提交按钮时,没有任何反应,只是刷新页面。

Here's my code:

这是我的代码:

app/Http/routes.php

应用程序/Http/routes.php

Route::group(['middleware' => ['web']], function () {
    Route::get('profile/edit', 'UserController@editProfile');
    Route::post('update_name', 'UserController@updateName');
});

app/Http/Request/UpdateNameRequest.php

应用程序/Http/Request/UpdateNameRequest.php

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use Illuminate\Support\Facades\Auth;

class UpdateNameRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'first_name' => 'required|min:2|alpha',
            'last_name' => 'required|min:2|alpha',
        ];
    }
}

app/Http/Controllers/UserController.php

应用程序/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;
use App\User;

class UserController extends Controller
{
    public function __construct() {
        $this->middleware('auth');
    }

    public function editProfile() {
        if (Auth::user()->role_id === 3) {
            return view('profile.crew.edit');          
        }
    }

    public function updateName(Requests\UpdateNameRequest $request) {
        return dd($request->all());
    }
}

and here's the html form

这是 html 表单

{!! Form::open(array('url' => 'update_name')) !!}
<div class="form-group{{ $errors->has('first_name') ? ' has-error' : '' }}">
    <label class="control-label">First Name</label>
    <input type="text" class="form-control" name="first_name" value="{{ old('first_name') }}" placeholder="{{ Auth::user()->first_name }}">

    @if ($errors->has('first_name'))
        <span class="help-block">
            <strong>{{ $errors->first('first_name') }}</strong>
        </span>
    @endif
</div>
<div class="form-group{{ $errors->has('last_name') ? ' has-error' : '' }}">
    <label class="control-label">Last Name</label>
    <input type="text" class="form-control" name="last_name" value="{{ old('last_name') }}" placeholder="{{ Auth::user()->last_name }}">

    @if ($errors->has('last_name'))
        <span class="help-block">
            <strong>{{ $errors->first('last_name') }}</strong>
        </span>
    @endif
</div>
<button type="submit" class="btn btn-success">Update name</button>
{!! Form::close() !!}

for reference heres the form output

供参考这里的表单输出

<form method="POST" action="http://localhost:8000/update_name" accept-charset="UTF-8">
    <input name="_token" type="hidden" value="VViupfPaPCQCk5aeUdc27Pt2Z8J7Hx1Y2khC0IY9">
    <div class="form-group">
        <label class="control-label">First Name</label>
        <input type="text" class="form-control" name="first_name" value="" placeholder="Hans">

    </div>
    <div class="form-group">
        <label class="control-label">Last Name</label>
        <input type="text" class="form-control" name="last_name" value="" placeholder="Padberg">

    </div>
    <button type="submit" class="btn btn-success">Update name</button>
</form>

here's my output in php artisan route:list

这是我在 php artisan route:list 中的输出

+--------+----------+-------------------------+------+-----------------------------------------------------------------+--------------+
| Domain | Method   | URI                     | Name | Action                                                          | Middleware   |
+--------+----------+-------------------------+------+-----------------------------------------------------------------+--------------+
|        | GET|HEAD | /                       |      | Closure                                                         | web          |
|        | GET|HEAD | home                    |      | App\Http\Controllers\HomeController@index                       | web,web,auth |
|        | GET|HEAD | login                   |      | App\Http\Controllers\Auth\AuthController@showLoginForm          | web,guest    |
|        | POST     | login                   |      | App\Http\Controllers\Auth\AuthController@login                  | web,guest    |
|        | GET|HEAD | logout                  |      | App\Http\Controllers\Auth\AuthController@logout                 | web          |
|        | POST     | password/email          |      | App\Http\Controllers\Auth\PasswordController@sendResetLinkEmail | web,guest    |
|        | POST     | password/reset          |      | App\Http\Controllers\Auth\PasswordController@reset              | web,guest    |
|        | GET|HEAD | password/reset/{token?} |      | App\Http\Controllers\Auth\PasswordController@showResetForm      | web,guest    |
|        | GET|HEAD | profile                 |      | App\Http\Controllers\UserController@getProfile                  | web,web,auth |
|        | GET|HEAD | profile/edit            |      | App\Http\Controllers\UserController@editProfile                 | web,web,auth |
|        | GET|HEAD | register                |      | App\Http\Controllers\Auth\AuthController@showRegistrationForm   | web,guest    |
|        | POST     | register                |      | App\Http\Controllers\Auth\AuthController@register               | web,guest    |
|        | POST     | update_email            |      | App\Http\Controllers\UserController@updateEmail                 | web,web,auth |
|        | POST     | update_name             |      | App\Http\Controllers\UserController@updateName                  | web,web,auth |
|        | POST     | update_password         |      | App\Http\Controllers\UserController@updatePassword              | web,web,auth |
|        | POST     | update_profile_picture  |      | App\Http\Controllers\UserController@updateProfilePicture        | web,web,auth |
+--------+----------+-------------------------+------+-----------------------------------------------------------------+--------------+

采纳答案by Bashar Nozibulla

Your error variable is returning empty value. Thats why no errors is showing just seeming the page is being refreshed. Ur validation is working but error value is not showing.

您的错误变量返回空值。这就是为什么没有错误显示只是看起来页面正在刷新。Ur 验证有效,但未显示错误值。

Try it: In app\Http\Kernel.php move \Illuminate\Session\Middleware\StartSession::classfrom the web$middlewareGroupsto $middleware

试试看:在 app\Http\Kernel.php 中\Illuminate\Session\Middleware\StartSession::classweb$middlewareGroups$middleware

回答by Mhmd

I just want to add Something for those who check the validation with postman or any other applications in this category, make sure you add

我只想为那些使用邮递员或此类别中的任何其他应用程序检查验证的人添加一些内容,请确保添加

Accept: application/json

接受:应用程序/json

to Header tab or you will not get application error and the page is just refreshed and return 200

到 Header 选项卡,否则您将不会收到应用程序错误并且页面刚刚刷新并返回 200

回答by emurmotol

I solved the problem I changed this:

我解决了这个问题,我改变了这个:

Route::group(['middleware' => ['web']], function () {
    Route::get('profile/edit', 'UserController@editProfile');
    Route::post('update_name', 'UserController@updateName');
});

to:

到:

Route::group(['middleware' => ['auth']], function () {
    Route::get('profile/edit', 'UserController@editProfile');
    Route::post('update_name', 'UserController@updateName');
});

Thank you guys :)

谢谢你们 :)

回答by J. Doe

Have you installed the Form Builder? Laravel Collective have made a guide on how to install the HTML & Form Facades. You can find it here: https://laravelcollective.com/docs/5.2/html

您是否安装了表单生成器?Laravel Collective 制作了一个关于如何安装 HTML & Form Facades 的指南。你可以在这里找到它:https: //laravelcollective.com/docs/5.2/html

回答by mrberggg

Not sure exactly what it is but here are a couple of things to try:

不确定它到底是什么,但这里有几件事可以尝试:

Explicitly add method => post

显式添加 method => post

{!! Form::open(array('url' => 'update_name', 'method' => 'post')) !!}

Check your routes to make sure the route is correctly registered. Run:

检查您的路线以确保路线已正确注册。跑:

`php artisan route:list`

If all else fails try using Postmanto manually send a POST request. This will at least let you identify whether the issue is in your form or in setting up the POST route.

如果所有其他方法都失败,请尝试使用Postman手动发送 POST 请求。这至少可以让您确定问题是在您的表单中还是在设置 POST 路由中。

Lastly, not related to this issue, I'd recommend keeping it simple. On a route like this there's not any need to have a Request class, just use inline validation.

最后,与此问题无关,我建议保持简单。在这样的路线上,不需要有 Request 类,只需使用内联验证。

public function updateName(Illuminate\Http\Request $request) {
    $this->validate($request, [
        'first_name' => 'required',
        'last_name' => 'required'
    ]);
    return dd($request->all());
}

回答by Kamal Saleh

You are getting TokenMismatchException .. make sure your session storage path is writable

您收到 TokenMismatchException .. 确保您的会话存储路径可写

回答by Eliasu

You can also get this error if the number of fields you are validating is more than there is on the submitted form.

如果您正在验证的字段数量多于提交的表单上的数量,您也可能会收到此错误。

Make sure that you are not validating more fields that there is on the submitted form.

确保您没有验证提交的表单上的更多字段。