简体   繁体   English

如果验证方法因 Laravel 失败,如何重定向回来

[英]How to redirect back if validate method fails with Laravel

I am using Laravel 6. I created a form to insert a meeting and I created a validate method in the controller to check if the data inserted in the db are correct.我正在使用 Laravel 6。我创建了一个表单来插入会议,并在 controller 中创建了一个验证方法来检查插入到数据库中的数据是否正确。 Unfortunately when the validate method fails the default redirect back deletes every field that has been compiled by the user.不幸的是,当验证方法失败时,默认重定向会删除用户编译的每个字段。

I tried many times but I am unable to understand how to do in case of failure a redirect back with the previous values filled in by the user.我尝试了很多次,但我无法理解在失败的情况下如何使用用户填写的先前值进行重定向。

Controller: Controller:

    {

        $this->validate($request, [
            'participants' => [ 'required', new CheckParticipant() ], 
            'description' => 'required',
            'room' => [ 'required', new CheckRoom() ],
            'date_meeting' => [ 'required', new CheckDateTime() ],
            'start' => [ 'required', new CheckTime() ],
            'end' => 'required',
        ]);

        $meeting = new Meeting();

        $participants = request('participants');
        $meeting->id_participants = implode(';', $participants);

        $meeting->description = request('description');
        $meeting->id_room = request('room');
        $meeting->date = request('date_meeting');
        $meeting->start_hour = request('start');
        $meeting->end_hour = request('end');

        $meeting->save();

        $message_correct = "The meeting has been correctly inserted!";

        return redirect()->route('home')->with('success', $message_correct);

    }

Finally if the user filled in for example the name of a participant to the meeting but the validate method fails I would like that the participant appears already selected in the dropdown menu after the default redirect back.最后,如果用户填写了例如会议参与者的姓名但验证方法失败,我希望参与者在默认重定向后出现在下拉菜单中已选中。 Is someone able to help me?有人可以帮助我吗?

In your view, you can use the old function to retrieve data flashed from the previous request.在您看来,您可以使用的 function 来检索从上一个请求中闪现的数据。

Instead of calling $this->validate try this:而不是调用$this->validate试试这个:

$validator = Validator::make($request->all(), [
    'participants' => [ 'required', new CheckParticipant() ], 
    'description' => 'required',
    'room' => [ 'required', new CheckRoom() ],
    'date_meeting' => [ 'required', new CheckDateTime() ],
    'start' => [ 'required', new CheckTime() ],
    'end' => 'required',
]);

if($validator->fails()) {
    return redirect('your/url')
    ->withErrors($validator)
    ->withInput();
}

Then, in your view you can access the old inputs with old('yourValue') .然后,在您看来,您可以使用old('yourValue')访问旧输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM