Laravel5表单验证

关于验证的更多资料参考:http://laravelacademy.org/post/240.html

直接上代码

模板部分:
<h1>填写留言内容</h1>
@if (count($errors) > 0)
    <!-- Form Error List -->
    <div class="alert alert-danger">
        <strong>Whoops! Something went wrong!</strong>

        <br><br>

        <ul>
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
        </ul>
    </div>
@endif
<form action="/message/add" method="POST">
    昵称:<input type="text" name="data[name]" value=""><br/>
    留言内容:<textarea name="data[body]" id="" cols="30" rows="10"></textarea>

    <button>提交</button>
</form>
控制器部分
public function postAdd(Request $request)
{
    $validator = Validator::make($request->input('data'), [
        'name' => 'required|max:255',
        'body' => 'required',
    ]);
    if ($validator->fails()) {
        //验证不通过
        return redirect('message/add')
            ->withErrors($validator)
            ->withInput();
    }
    //验证通过,保存留言信息
    $message = new Message;
    $message->name = $request->name;
    $message->body = $request->body;
    $result = $message->save();
    return redirect('message/index');
}

发表评论

邮箱地址不会被公开。 必填项已用*标注