重定向回来,输入不在laravel 5.5中

时间:2018-05-08 09:12:46

标签: laravel redirect input laravel-5.5 back

之前我曾多次使用重定向输入。但在这个项目中,我无法这样做。这是我处理表单请求的控制器方法:

public function verifyMobileCode( Request $request)
{
        $userId = Auth::user()->id;
        if( Auth::user()->verification_code == $request['verification_code'])
        {
            User::where('id', $userId)->update(['verified'=>1]);
            return redirect('/')->with('success', 'Account verified.');
        }
        else
        {
            return redirect()->back()->withErrors('verification_code' ,'unv' )->withInput($request->all());
        }
}

这是我的表格:

@extends('layouts.index')

@section('content')

<div class="container" style='padding-top: 150px;'>

    <?php var_dump($errors) ; ?>
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Verify your mobile</div>

                <div class="panel-body">
                    <form class="form-horizontal" method="POST" action="{{ route('verifyMobileCode') }}">
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('verification_code') ? ' has-error' : '' }}">
                            <label for="verification_code" class="col-md-4 control-label">Verification code</label>

                            <div class="col-md-6">
                                <input id="verification_code" type="text" class="form-control" name="verification_code" value="{!! old('verification_code') !!}" required autofocus maxlength="6" pattern="\d{6}">

                                @if ($errors->has('verification_code'))
                                    <span class="help-block">
                                        <strong>Please enter 6 digit number sent to your mobile.</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Register
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

My Kernel.php如下:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \App\Http\Middleware\LanguageSwitcher::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'is-admin' => \App\Http\Middleware\IsAdminMiddleware::class,
    ];
}

我没有发现任何错误或错误。你看到了什么吗?是否有任何技术来调试此行为?提前完成。

7 个答案:

答案 0 :(得分:3)

我的方法是使用FormRequest

php artisan make:request VerifyCodeRequest

请求的正文:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class VerifyCodeRequest 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()
    {
        return [
            'verification_code' => 'required|in:'.$this->user()->verification_code, // since user is already logged in we check if verification_code matches using `in` rule
        ];
    }


    public function messages()
    {
        return [
            'in' => 'Your custom error message if we failed',
        ];
    }
}

现在,您将verifyMobileCode(...)的签名更改为以下verifyMobileCode(App\Http\Requests\VerifyCodeRequest $request)

现在,只有当我们通过验证时,代码才会执行​​函数的主体,所以我们需要更新用户实例,我们就完成了。

public function verifyMobileCode(App\Http\Requests\VerifyCodeRequest $request)
{
    $request->user()->verify();
    return redirect('/')->with('success', 'Account verified.');
}

内部用户模型添加verify()功能

public function verify() 
{
    $this->update(['verified' => true]);
}

如果您的上述方法不起作用,则 app/Http/Kernel.php 会出现问题。你用过了

\Illuminate\Session\Middleware\StartSession::class,

两次。你必须删除一个。可能是第一个。

查看Laravel的kernel.php股票。

答案 1 :(得分:0)

->withInput($request->all());替换为->withInput();

如果您不想使用任何一个输入

->withInput( $request->except('input_name') );

答案 2 :(得分:0)

要在不使用Xdebug的情况下进行调试,快速的方法是将临时调试代码添加到刀片文件的开头:

@php
    dd($errors->toArray(), $errors->has('verification_code'));
@endphp

这会给你以下输出:

array:1 [
  0 => array:1 [
    0 => "verification_code"
  ]
]
false

这表明刀片文件中的逻辑未被评估为 true ,这是显示错误样式和消息所必需的。

快速解决方法是将控制器更改为使用:

->withErrors(['verification_code' => 'unv'])

withErrors期望为MessageBag或数组,但会将字符串强制转换为不会产生正确键/值对的数组。

现在将显示调试输出:

array:1 [
  "verification_code" => array:1 [
    0 => "unv"
  ]
]
true

现在可以删除调试代码,并且应该按预期显示错误。

正确的Laravel方式可能是对复杂表单使用$ request-&gt; validate()或FormRequest。有关更多信息,请参阅Laravel验证文档(https://laravel.com/docs/5.5/validation)。

答案 3 :(得分:0)

return redirect()->back()->withInput()->withErrors('verification_code' ,'unv' );

答案 4 :(得分:0)

您的控制器应如下所示:

public function verifyMobileCode( Request $request)
{
    $userId = Auth::user()->id;
    if( Auth::user()->verification_code == $request['verification_code'])
    {
        User::where('id', $userId)->update(['verified'=>1]);
        return redirect('/')->with('success', 'Account verified.');
    }
    else
    {
        return redirect()->back()->withErrors('message' ,'Please some errors encountered.' );
    }
}

并修改此

<div class="form-group{{ $errors->has('verification_code') ? ' has-error' : '' }}">

对此:

<div class="form-group>
@include('errors');

还在资源/视图中创建名为errors.blade.php的文件,并输入以下代码:

@if ($errors->any())
<div class="card"> //incase bootstrap 4
    <div class="error card-body alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
</div>
@endif

希望它适合你。但是你不需要显示旧的输入,因为代码会出错或出现错误。所以没必要

答案 5 :(得分:0)

在控制器中

return redirect()->back()->withErrors('verification_code' ,'unv')->withInput();

可见

如果要检索经过验证的输入字段值,则需要对FORM<form></form>字段使用laravel <input>

示例

{{ Form::open(['method' => 'post','url' => 'Your url','class'=>'form-horizontal']) }}

     {{ Form::text('verification_code','',['class'=>'form-control']) }}

{{ Form::close() }}

答案 6 :(得分:0)

Laravel 8 上的任何人,这都应该有效

return back()->withErrors('your error message is here');

如果您查看 withErrors 函数的签名,则第二个参数是键,除非您希望它是特定的,否则它被设置为 default