欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Laravel框架表單驗證操作實例分析

 更新時間:2019年09月30日 10:10:11   作者:學(xué)知無涯  
這篇文章主要介紹了Laravel框架表單驗證操作,結(jié)合實例形式分析了Laravel框架表單驗證相關(guān)的表單數(shù)據(jù)提交、驗證、錯誤信息提示等相關(guān)操作技巧,需要的朋友可以參考下

本文實例講述了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)文章

最新評論