如何在laravel中通过验证更新表单?

时间:2019-03-05 16:09:15

标签: laravel-5 eloquent

我的表单验证在Laravel中不起作用。如何在Laravel中通过验证更新表单?

您可以在此处查看我的代码-

public function update(Request $request, $id)
{
    $id->validate([
        'Name'=>'required',
        'UserName'=>'required',
        'Password'=>'required|min:6',
        'email'=>'required|email',
    ]);

    $updateInfo= Info::findOrFail($id);
    $updateInfo->user_id = $request->input('user_id');
    $updateInfo->Name = $request->input('Name');
    $updateInfo->UserName = $request->input('UserName');
    $updateInfo->Password = $request->input('Password');
    $updateInfo->save();

    return redirect('/info');
}

2 个答案:

答案 0 :(得分:0)

您需要在$ request上调用validate,像这样-

$request->validate([
    'Name'=>'required',
    'UserName'=>'required',
    'Password'=>'required|min:6',
    'email'=>'required|email',
]);

这是完整的代码-

public function update(Request $request, $id)
{
    $request->validate([
        'Name'=>'required',
        'UserName'=>'required',
        'Password'=>'required|min:6',
        'email'=>'required|email',
    ]);

    if (!$validator->fails()) {
        $updateInfo= Info::findOrFail($id);
        $updateInfo->user_id = $request->input('user_id');
        $updateInfo->Name = $request->input('Name');
        $updateInfo->UserName = $request->input('UserName');
        $updateInfo->Password = $request->input('Password');
        $updateInfo->save();
    } else {
       \Session::flash('error', $validator->messages()->first());

        return redirect()->back()->withInput();
    }


    return redirect('/info');
}

我在代码中添加了另一个条件来处理验证错误。如果验证失败,则它将重定向回您的输入以及验证错误消息。确保刀片视图中有错误会话闪存,以显示错误。

答案 1 :(得分:0)

对我来说,这是最好的方法,我可以将其放在try catch块中,以跟踪查询和其他异常情况

public function update(Request $request, $id)
    {
        try{
            $validator = Validator::make($request->all(), [
                'name'          => 'required',
                'UserName'      => 'required',
                'Password'      => 'required',
                'email'         => 'required|email',
            ]);
            if($validator->fails()) {
                return redirect()
                    ->route('path_to_edit_form')
                    ->withErrors($validator)
                    ->withInput();
            }
            Info::where('id',$id)->update([
                'user_id'    => $request->get('user_id'),
                'Name'       => $request->get('Name'),
                'UserName'   => $request->get('UserName'),
                'Password'   => $request->get('Password'),
            ]);
            return back()->with([
                'alert_type'    => 'success',
                'message'       => 'User info updated successfully.'
            ]);
        }catch(\Exception $e){
            return back()->with([
                'alert_type'    => 'danger',
                'message'       => $e->getMessage()
            ]);
        }
    }