Laravel框架表單驗證操作實例分析
本文實例講述了Laravel框架表單驗證操作。分享給大家供大家參考,具體如下:
public function create(Request $request){
if($request->isMethod('POST')){
//驗證通過后繼續(xù)進行
//方法1 控制器驗證
$this->validate($request,[
'Student.name' => 'required|min:2|max:20',
'Student.age' => 'required|integer',
'Student.sex' => 'required|integer',
],[
'required'=>':attribute 為必填項',
'min' => ':attribute 長度不符合要求',
'integer' => ':attribute 必須是一個整形',
],[ 'Student.name' => '姓名',
'Student.age' => '年齡',
'Student.sex' => '性別',
]);
//方法2 Validator類驗證
$validator = \Validator::make($request->input(),[
'Student.name' => 'required|min:2|max:20',
'Student.age' => 'required|integer',
'Student.sex' => 'required|integer',
],[
'required'=>':attribute 為必填項',
'min' => ':attribute 長度不符合要求',
'integer' => ':attribute 必須是一個整形',
],[ 'Student.name' => '姓名',
'Student.age' => '年齡',
'Student.sex' => '性別',
]);
if($validator->fails()){
return redirect()->back()->withErrors($validator)->withInput();
}
//如果驗證通過,則繼續(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中間件有個作用是防止xss攻擊,即csrf,需要在頁面的表單中增加{{ csrf_field() }},
會生成一個隱藏的input表單,帶個token字段。
錯誤信息的顯示:
控制器中的with方法,可以把信息放入session中
return redirect('Student/index')->with('success','添加成功');
頁面中的顯示:
@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()}}可以顯示第一條錯誤信息
數(shù)據(jù)保持:
return redirect()->back()->withErrors($validator)->withInput();
這段代碼中的withInput可以把表單提交的信息帶回去,
頁面中使用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)容感興趣的讀者可查看本站專題:《Laravel框架入門與進階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家基于Laravel框架的PHP程序設(shè)計有所幫助。
相關(guān)文章
php從數(shù)據(jù)庫讀取數(shù)據(jù),并以json格式返回數(shù)據(jù)的方法
今天小編就為大家分享一篇php從數(shù)據(jù)庫讀取數(shù)據(jù),并以json格式返回數(shù)據(jù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
基于AppServ,XAMPP,WAMP配置php.ini去掉警告信息(NOTICE)的方法詳解
本篇文章是對AppServ,XAMPP,WAMP配置php.ini去掉警告信息(NOTICE)的方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05
TP5框架實現(xiàn)一次選擇多張圖片并預(yù)覽的方法示例
這篇文章主要介紹了TP5框架實現(xiàn)一次選擇多張圖片并預(yù)覽的方法,結(jié)合實例形式詳細分析了thinkPHP5基于ajax數(shù)據(jù)提交上傳多張圖片與本地預(yù)覽相關(guān)操作技巧,需要的朋友可以參考下2020-04-04
使用ThinkPHP的自動完成實現(xiàn)無限級分類實例詳解
這篇文章主要介紹了使用ThinkPHP的自動完成實現(xiàn)無限級分類功能,本文通過圖文并茂的方式給大家展示,介紹的非常詳細,具有參考借鑒價值,感興趣的朋友一起看看吧2016-09-09

