Laravel 5 在请求失败时返回模型数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30789267/
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 11:46:30  来源:igfitidea点击:

Laravel 5 on failed request return back with model data

phpvalidationlaravellaravel-5

提问by Szenis

EDIT
This issue has been solved, but I don't understand why the answer worked.
I would like to know why it didnt work. Is there some one who could explain me?

编辑
此问题已解决,但我不明白为什么答案有效。
我想知道为什么它不起作用。有哪位大神能解释一下吗?



Original question
I am stuck on my settings form, my problem is that at the settings form you can enter some email settings but you can also change your password.

原始问题
我被困在我的设置表单上,我的问题是在设置表单中您可以输入一些电子邮件设置,但您也可以更改密码。

The email settings and password reset works and my form fills it self with the data of the current user. Butwhen the form validation fails it redirecteds me back to the form without the form data.

电子邮件设置和密码重置有效,我的表单用当前用户的数据自行填充。但是当表单验证失败时,它会将我重定向回没有表单数据的表单。

I am not sure if I made myself clear, but this code below will explain it.

我不确定我是否说清楚了,但下面的代码将解释它。

ChangeUserSettingRequest.php

更改用户设置请求.php

class ChangeUserSettingsRequest extends Request {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        if (\Auth::check()) {
            return true;
        }
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * WHEN THIS VALIDATION FAILS IT GOES BACK TO SETTINGS.BLADE.PHP 
     * BUT IT DOES NOT KEEP THE SETTINGS DATA IN THE FORM
     */
    public function rules()
    {
        return [
            'current_password' => 'sometimes|required_with:password',
            'password' => 'required_with:current_password|min:8|confirmed',
            'password_confirmation' => 'required_with:password',
        ];
    }

}

settings.blade.php

settings.blade.php

{!! Form::model($settings, array('url' => route('store.settings'), 'class' => 'col s12')) !!}

    <p>@lang('forms.info.settings')</p>

    <div class="input-field col s12 m6 l6">
        {!! Form::checkbox('info_mail', 0, false, ['id' => 'info_mail']) !!}
        {!! Form::label('info_mail', Lang::get('forms.newsletter'), ['for' => 'info_mail']) !!}
    </div>
    <div class="input-field col s12 m6 l6">
        {!! Form::checkbox('message_notification', 0, false, ['id' => 'message_notification']) !!}
        {!! Form::label('message_notification', Lang::get('forms.messages'), ['for' => 'message_notification']) !!}
    </div>
    <div class="input-field col s12 m6 l6">
        {!! Form::checkbox('friend_notification', 0, false, ['id' => 'friend_notification']) !!}
        {!! Form::label('friend_notification', Lang::get('forms.friendrequest'), ['for' => 'friend_notification']) !!}
    </div>
    <div class="input-field col s12 m6 l6">
        {!! Form::checkbox('item_notification', 0, false, ['id' => 'item_notification']) !!}
        {!! Form::label('item_notification', Lang::get('forms.reactiononitem'), ['for' => 'item_notification']) !!}
    </div>

    @if ($settings and $settings->google_maps !== null)
        <div class="settings-explain">
            <p class="margin-top-20">@lang('forms.info.companysettings')</p>
        </div>
        <div class="input-field col s12 m6 l6">
            {!! Form::checkbox('type', 0, false, ['id' => 'type']) !!}
            {!! Form::label('type', Lang::get('forms.companytype'), ['for' => 'type']) !!}
        </div>
        <div class="input-field col s12 m6 l6">
            {!! Form::checkbox('google_maps', 0, false, ['id' => 'google_maps']) !!}
            {!! Form::label('google_maps', Lang::get('forms.companymap'), ['for' => 'google_maps']) !!}
        </div>
    @endif

    <div class="settings-explain">
        <p class="margin-top-20">@lang('forms.info.changepassword')</p>
    </div>
    <div class="input-field col s12">
        {!! Form::label('current_password', $errors->has('current_password') ? $errors->first('current_password') : Lang::get('forms.currentpassword'), ['for' => 'current_password']) !!}
        {!! Form::password('current_password', ['class' => $errors->has('current_password') ? 'invalid' : '']) !!}
    </div>
    <div class="input-field col s12">
        {!! Form::label('password', $errors->has('password') ? $errors->first('password') : Lang::get('forms.newpassword'), ['for' => 'password']) !!}
        {!! Form::password('password', ['class' => $errors->has('password') ? 'invalid' : '']) !!}
    </div>  
    <div class="input-field col s12">
        {!! Form::label('password_confirmation', $errors->has('password_confirmation') ? $errors->first('password_confirmation') : Lang::get('forms.repeatpassword'), ['for' => 'password_confirmation']) !!}
        {!! Form::password('password_confirmation', ['class' => $errors->has('password_confirmation') ? 'invalid' : '']) !!}
    </div>
    <div class="input-field col s12">
        {!! Form::button(Lang::get('forms.save'), ['class' => 'btn waves-effect waves-light', 'type' => 'submit', 'name' => 'Save']) !!}
    </div>
{!! Form::close() !!}

UserInfoController.php

用户信息控制器.php

/**
 *  Function shows the settings form
 */
public function showSettings() 
{
    $title = Lang::get('titles.settings');
    $user_id = Auth::User()->id;

    $settings = $this->settings->getUserSettings($user_id);
    $companySettings = $this->companySettings->getSettings($user_id);

    if ($companySettings) {
        $settings->type = $companySettings->type;
        $settings->google_maps = $companySettings->google_maps;
    }

    return view('pages.users.settings', ['title' => $title])->with(compact('settings'));
}

/**
 *  Function stores the setting changes
 *
 *  ChangeUserSettingsRequest makes sure that the request is valid
 */
public function storeSettings(ChangeUserSettingsRequest $request)
{
    $id = Auth::User()->id;
    $success = $this->settings->handleStoreSettingsRequest($request);

    // Checks if user has company settings
    $hasCompanySettings = $this->companySettings->checkForSettings($id);

    // If user has company settings
    if ($hasCompanySettings === true) {
        // Update company settings
        $this->companySettings->updateSettings($request);
    }

    if ($success === true) {

        /* Get translated message */
        $message = Lang::get('toast.settingsstored');
        return Redirect::route('user.profile', array(Auth::User()->permalink))->withMessage($message);
    }

    $settings = $this->settings->getUserSettings($id);

    /* Get translated message */
    $message = Lang::get('forms.error.wrongpassword');

    /* This works and the form is filled with the correct data after it  redirects me back */
    return Redirect::back()->withErrors(array('current_password' => $message))->withSettings($settings);
}

Request.php

请求文件

use Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest {

    //

}

So my problem is that in my UserInfoControllerI redirect back and it has the good data but when my ChangeUserSettingsRequestredirects me back the form is empty.

所以我的问题是,在我的UserInfoController 中,我重定向回来并且它具有良好的数据,但是当我的ChangeUserSettingsRequest将我重定向回来时,表单是空的。

Does anyone know why ChangeUserSettingsRequest does not send the data back?

有谁知道为什么 ChangeUserSettingsRequest 不发回数据?

  • I am not talking about the password data but about the email settings.
  • I do not want to make a costum validator as I think this should be posible.
  • 我不是在谈论密码数据,而是在谈论电子邮件设置。
  • 我不想制作服装验证器,因为我认为这应该是可行的。

Please note: when the validation fails, the function storeSettingswill not be executed at all

请注意:当验证失败时,该函数storeSettings根本不会被执行

采纳答案by Szenis

I found it!

我找到了!

The formRequest should have handled it correctly but no idea why it did not.
I found the solution when looking trough the file formRequest.php https://github.com/laravel/framework/blob/master/src/Illuminate/Foundation/Http/FormRequest.php

formRequest 应该正确处理它,但不知道为什么没有。
我在查看文件 formRequest.php https://github.com/laravel/framework/blob/master/src/Illuminate/Foundation/Http/FormRequest.php时找到了解决方案

I had to overridethe response functionand it works now!
To only thing that I had to add to my ChangeUserSettingsRequestwas this

我不得不重写响应函数和它的作品吧!
我必须添加到我的唯一的东西ChangeUserSettingsRequest是这个

public function response(array $errors)
{
    return $this->redirector->to($this->getRedirectUrl())->withErrors($errors, $this->errorBag);
}

The only difference is that I don't send the input fields back, little strange that this works but I am glad that it is solved now.

唯一的区别是我不发回输入字段,这很奇怪,但我很高兴它现在已经解决了。

回答by JustinM151

On failure return them back to the page with their input data (withInput())

失败时将它们返回到带有输入数据的页面(withInput())

return Redirect::back()->withErrors(['current_password' => $message])->withInput($request->except('password'));

For more information see the Laravel docs pertaining to requests... http://laravel.com/docs/5.1/requests

有关更多信息,请参阅有关请求的 Laravel 文档... http://laravel.com/docs/5.1/requests