laravel框架学习记录之表单操作详解

吾爱主题 阅读:150 2021-09-27 11:22:00 评论:0

本文实例讲述了laravel框架学习记录之表单操作。分享给大家供大家参考,具体如下:

1、MVC数据流动

拿到一个laravel项目最基本的是弄清楚它的页面请求、数据流动是怎样进行的,比如当通过get请求index页面时,如何显示如下的学生信息列表:

首先当一个页面请求到达时,需要在routes/web.php中定义路由请求以及对应的处理方法:

?
1 Route::get( 'index' , 'StudentController@getIndex' );

然后在.env文件下设置好数据库连接,新建数据库模型Student放在app/目录下,在其中指定对应的数据表为student

?
1 2 3 4 5 class Student extends Model {    protected $table = 'student' ;       //指定数据库    protected $fillable =[ 'name' , 'age' , 'sex' ];  //允许修改的字段 }

新建控制类StudentController并实现getIndex方法,在getIndex方法中调用student/index.blade.php页面,并通过Student模型查询到学生信息传递给view

?
1 2 3 public static function getIndex(){    return view( 'student.index' ,[ 'students' =>Student::paginate(5)]); }

实现页面视图,在resources/views文件夹下新建student文件夹用于存放student相关页面。

采用模板的思路来实现index页面:新建页面的模板文件layout.blade.php文件,保留其中的公共部分,将其中不同的地方通过@section或者@yield替换。新建index.blade.php继承layout模板公共的部分,并在其中实现index页面自定义的部分

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @ extends ( 'student.layout' ) @section( 'title' )    主页    @stop @section( 'content' )    <!-- index页面自定义内容-->    @stop      在自定义内容里通过@ foreach 将学生数据信息循环显示到列表 @ foreach ( $students as $student )    <tr>      <th scope= "row" >{{ $student ->id}}</th>      <td>{{ $student ->name}}</td>      <td>{{ $student ->age}}</td>      <td>{{ $student ->sex}}</td>      <td>{{ $student ->created_at}}</td>    </tr> @ endforeach

这样,当用户通过get请求index页面时,学生数据就从数据库中取出并展示到了页面内。

2、在blade中引入页面资源文件

虽然视图文件放在resources/views目录下,但是blade文件编译完成后将位于public目录下,所以其中的目录是相对于public而言的,页面所需要的静态资源应该放在public目录下并通过asset函数相对public路径来引入。

laravel默认提供了bootstrap与jquery,分别对应于public/css/app.css与public/js/app.js文件,如果需要可以引入。

?
1 2 3 4 <!-- Bootstrap CSS 文件 --> <link rel= "stylesheet" href= "{{ asset('./css/app.css')}}" rel= "external nofollow" > <!-- jQuery 文件 --> <script src= "{{ asset('./js/app.js')}}" ></script>

3、laravel中实现分页

在laravel中可以很便捷地实现分页数据显示,第一步是在controller中分页取出数据库数据并传递给页面:

?
1 return view( 'student.index' ,[ 'students' =>Student::paginate(5)]);

第二部在页面内渲染分页标签:

?
1 2 3 <ul class = "pagination pull-right" >    {{ $students ->render()}} </ul>

4、表单验证

laravel提供了validate方法来用于验证用户提交的表单是否符合要求,例如在页面通过post提交了学生表单form后,在controller中对其先进行验证,如果正确则存入数据库,否则返回到上一页面并抛出一个异常$errors,在页面中显示错误$errors中的信息

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 //表单验证 $request ->validate([    'Student.name' => 'required|max:10' ,    'Student.age' => 'required|integer' ,    'Student.sex' => 'required' , ],[    'required' => ':attribute为必填项' ,    'max' => ':attribut长度过长' ,    'integer' => ':attribute必须为一个整数' ],[    'Student.name' => '姓名' ,    'Student.age' => '年龄' ,    'Student.sex' => '性别' ]); //存入学生数据 $stu = $request ->input( 'Student' ); Student::create( $stu );

validate()中第一个数组中定义字段的验证规则,其中Student.name是在提交的表单中定义的name

?
1 input type="text" name="Student[name]" placeholder="请输入学生姓名">

required是你所需要的验证规则,中间用"|"隔开,详细的规则可以看文档

validate()第二个数组自定义验证出错后的提示信息,":attribute"为占位符

validate()第三个数组自定义每个字段的提示名字

在页面中报错如下:

可以通过$errors->all()获取所有错误后循环显示出来

?
1 2 3 4 5 6 7 8 9 @ if ( count ( $errors ))    <div class = "alert alert-danger" >      <ul>        @ foreach ( $errors ->all() as $error )          <li>{{ $error }}</li>          @ endforeach      </ul>    </div>    @ endif

也可以$errors->first()获取指定字段的验证错误,显示在每个输入框之后

?
1 < p class = "form-control-static text-danger" >{{$errors->first('Student.name')}}</ p >

当验证失败返回到表单页面后,用户原来的输入信息会消失,这样需要再填一遍,可以通过old方法显示用户原来的输入

?
1 <input type= "text" name= "Student[name]" value= "{{old('Student')['name']}}" >

5、错误记录

①、 MethodNotAllowedHttpException No message

这个错误是因为我把表单的post请求发送到了Route::get()定义的路由上,它不会处理post请求,可以把路由通过Route::Match(['get','post'],)来定义

②、Action App\Http\Controllers\StudentController@delete not defined

这个错误发生在我将在blade页面请求跳转到一个action,无法找到该Controller

?
1 <a href= "{{action('StudentController@delete',['id'=>$student->id])}}" rel= "external nofollow" >删除</a>

但当我在routes/web.php下注册了该方法后报错消失

?
1 Route::get( 'delete/{id}' , 'StudentController@delete' );

③、The page has expired due to inactivity. Please refresh and try again.

这是由于laravel自动设置了防止CSRF跨域攻击,你需要在表单内添加csrf_filed()来告诉laravel请求的发起人与表单提交者是同一个人。

?
1 2 <form class = "form-horizontal" method= "post" action= "{{url('student/create')}}" >    {{ csrf_field() }}

希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。

原文链接:https://blog.csdn.net/theVicTory/article/details/80325669

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容