本文實(shí)例講述了Laravel框架表單驗(yàn)證操作。分享給大家供大家參考,具體如下:
public function create(Request $request){ if($request->isMethod('POST')){ //驗(yàn)證通過(guò)后繼續(xù)進(jìn)行 //方法1 控制器驗(yàn)證 $this->validate($request,[ 'Student.name' => 'required|min:2|max:20', 'Student.age' => 'required|integer', 'Student.sex' => 'required|integer', ],[ 'required'=>':attribute 為必填項(xiàng)', 'min' => ':attribute 長(zhǎng)度不符合要求', 'integer' => ':attribute 必須是一個(gè)整形', ],[ 'Student.name' => '姓名', 'Student.age' => '年齡', 'Student.sex' => '性別', ]); //方法2 Validator類(lèi)驗(yàn)證 $validator = \Validator::make($request->input(),[ 'Student.name' => 'required|min:2|max:20', 'Student.age' => 'required|integer', 'Student.sex' => 'required|integer', ],[ 'required'=>':attribute 為必填項(xiàng)', 'min' => ':attribute 長(zhǎng)度不符合要求', 'integer' => ':attribute 必須是一個(gè)整形', ],[ 'Student.name' => '姓名', 'Student.age' => '年齡', 'Student.sex' => '性別', ]); if($validator->fails()){ return redirect()->back()->withErrors($validator)->withInput(); } //如果驗(yàn)證通過(guò),則繼續(xù)執(zhí)行下面的代碼 $data = $request->input('Student'); if(Student::create($data)){ return redirect('student/index')->with('success','添加成功'); }else{ return redirect()->back(); } } return view('student.create'); }
注意Laravel的create方法,需要在model中
設(shè)置允許批量賦值:
protected $fillable = ['name','age'];
web中間件有個(gè)作用是防止xss攻擊,即csrf,需要在頁(yè)面的表單中增加{{ csrf_field() }},
會(huì)生成一個(gè)隱藏的input表單,帶個(gè)token字段。
錯(cuò)誤信息的顯示:
控制器中的with方法,可以把信息放入session中
return redirect('Student/index')->with('success','添加成功');
頁(yè)面中的顯示:
@if(Session::has('success')) div> {{ Session::get('success') }} /div> @endif @if(count($errors)) div class="alert alert-danger"> ul> @foreach($errors->all() as $val) li>{{$val}}/li> @endforeach /ul> /div> @endif
{{$errors->first()}}
可以顯示第一條錯(cuò)誤信息
數(shù)據(jù)保持:
return redirect()->back()->withErrors($validator)->withInput();
這段代碼中的withInput可以把表單提交的信息帶回去,
頁(yè)面中使用old方法:
姓名 :input type="text" name="Student[name]" value="{{ old('Student')['name'] }}" /> 性別 : @foreach($student->user_sex() as $ind=>$val) input type="radio" name="Student[sex]" value="{{$ind}}" {{ old('Student')['sex']==$ind?'checked':'' }} />{{$val}} @endforeach
更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Laravel框架入門(mén)與進(jìn)階教程》、《php優(yōu)秀開(kāi)發(fā)框架總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家基于Laravel框架的PHP程序設(shè)計(jì)有所幫助。
標(biāo)簽:南寧 山南 赤峰 濟(jì)寧 三亞 烏魯木齊 迪慶 鷹潭
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Laravel框架表單驗(yàn)證操作實(shí)例分析》,本文關(guān)鍵詞 Laravel,框架,表單,驗(yàn)證,操作,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。