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

Laravel框架表單驗(yàn)證操作實(shí)例分析

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

本文實(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類驗(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)容感興趣的讀者可查看本站專題:《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ì)有所幫助。

相關(guān)文章

最新評(píng)論