欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Laravel 表单

程序员文章站 2022-06-15 15:59:31
...

1. 静态资源管理以及模板布局;

  • public/statics/ 导入 Bootstrap 以及 jQuery 类库
    Laravel 表单
  • 新建 App/Http/Controllers/StudentController.php
<?php

namespace App\Http\Controllers;

class StudentController extends Controller{

    // 列表页
    public function index(){
        return view('student.index');
    }
    
}
  • routes/web.php 新建一条路由
<?php
Route::get('student/index', ['uses' => 'aaa@qq.com']);
  • 新建公共视图文件 resources/views/common/layouts.blade.php
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>轻松学会 Laravel - @yield('title')</title>
    <!-- Bootstrap CSS 文件 -->
    <link rel="stylesheet" href="{{ asset('static/bootstrap/css/bootstrap.min.css') }}">
    <!-- 子页面自己的样式 -->
    @section('style')

    @show
</head>
<body>

<!-- 头部 -->
@section('header')
    <div class="jumbotron">
        <div class="container">
            <h2>轻松学会 Laravel</h2>

            <p> - Laravel 表单</p>
        </div>
    </div>
@show

<!-- 中间内容区局 -->
<div class="container">
    <div class="row">

        <!-- 左侧菜单区域   -->
        <div class="col-md-3">
            @section('leftmenu')
                <div class="list-group">
                    <a href="#" class="list-group-item active">学生列表</a>
                    <a href="#" class="list-group-item">新增学生</a>
                </div>
            @show
        </div>

        <!-- 右侧内容区域 -->
        <div class="col-md-9">
            @yield('content')
           

        </div>
    </div>
</div>

<!-- 尾部 -->
@section('footer')
    <div class="jumbotron" style="margin:0;">
        <div class="container">
            <span>  {{ date('Y') }} test</span>
        </div>
    </div>
@show

<!-- jQuery 文件 -->
<script src="{{ asset('static/jquery/jquery.min.js') }}"></script>
<!-- Bootstrap JavaScript 文件 -->
<script src="{{ asset('static/bootstrap/js/bootstrap.min.js') }}"></script>

<!-- 自定义 js 文件-->
@section('Javascript')

@show

</body>
</html>

  • 新建公共视图文件 resources/views/common/message.blade.php
 <!-- 成功提示框 -->
 <div class="alert alert-success alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <strong>成功!</strong> 操作成功提示!
</div>

<!-- 失败提示框 -->
<div class="alert alert-danger alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <strong>失败!</strong> 操作失败提示!
</div>
  • 新建视图文件 resources/views/student/index.blade.php
 @extends('common.layouts')

 @section('content')

    <!-- 加载提示信息 -->
    @include('common.message')
        <!-- 自定义内容区域 -->
        <div class="panel panel-default">
            <div class="panel-heading">学生列表</div>
            <table class="table table-striped table-hover table-responsive">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>添加时间</th>
                    <th width="120">操作</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <th scope="row">1</th>
                    <td>Mark</td>
                    <td>18</td>
                    <td></td>
                    <td>2016-01-01</td>
                    <td>
                        <a href="">详情</a>
                        <a href="">修改</a>
                        <a href="">删除</a>
                    </td>
                </tr>
                <tr>
                    <th scope="row">1</th>
                    <td>Mark</td>
                    <td>18</td>
                    <td></td>
                    <td>2016-01-01</td>
                    <td>
                        <a href="">详情</a>
                        <a href="">修改</a>
                        <a href="">删除</a>
                    </td>
                </tr>
                <tr>
                    <th scope="row">1</th>
                    <td>Mark</td>
                    <td>18</td>
                    <td></td>
                    <td>2016-01-01</td>
                    <td>
                        <a href="">详情</a>
                        <a href="">修改</a>
                        <a href="">删除</a>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>

        <!-- 分页  -->
        <div>
            <ul class="pagination pull-right">
                <li>
                    <a href="#" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                <li class="active"><a href="#">1</a></li>
                <li><a href="#">2</a></li>
                <li><a href="#">3</a></li>
                <li><a href="#">4</a></li>
                <li><a href="#">5</a></li>
                <li>
                    <a href="#" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            </ul>
        </div>

@stop

2. 表单列表及分页实现;

  • 使用 ORM 的方式实现
  • 新建 app/Student.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model{

    // 指定表名
	protected $table = 'student';

	// 指定主键
    protected $primaryKey = 'id';

    // 自定义时间戳
    public $timestamps = true;

    public function getDateFormat(){
        return time();
    }

    protected function asDateTime($val){
        return $val;
    }

}
  • 修改 App/Http/Controllers/StudentController.php
<?php

namespace App\Http\Controllers;

use App\Student;

class StudentController extends Controller{

    // 列表页
    public function index(){
        //$student = Student::get();

       $student = Student::orderBy('id','desc')->paginate(2);    // 分页,每页显示 2 条

        return view('student.index',[
            'students' => $student
        ]);
    }

}
  • 修改视图文件 resources/views/student/index.blade.php
 @extends('common.layouts')

 @section('content')

    <!-- 加载提示信息 -->
    @include('common.message')
        <!-- 自定义内容区域 -->
        <div class="panel panel-default">
            <div class="panel-heading">学生列表</div>
            <table class="table table-striped table-hover table-responsive">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>添加时间</th>
                    <th width="120">操作</th>
                </tr>
                </thead>
                <tbody>
                    @foreach($students as $student)
                    <tr>
                        <th scope="row">{{ $student->id }}</th>
                        <td>{{ $student->name }}</td>
                        <td>{{ $student->age }}</td>
                        <td>{{ $student->gender }}</td>
                        <td>{{ date('Y-m-d H:i:s', $student->created_at) }}</td>
                        <td>
                            <a href="">详情</a>
                            <a href="">修改</a>
                            <a href="">删除</a>
                        </td>
                    </tr>
                    @endforeach
                
                </tbody>
            </table>
        </div>

        <!-- 分页  -->
        <div>
            <div class="pull-right">
                {{ $students->render() }}
            </div>
        </div>

@stop

3. 通过表单实现新增及操作状态提示功能;

  • 通过表单实现模型新增和 create 新增

  • 提交到当前方法和指定方法

  • 修改 App/Http/Controllers/StudentController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\Student;

class StudentController extends Controller{

    // 列表页
    public function index(){
        //$student = Student::get();
		
        $student = Student::orderBy('id','desc')->paginate(2);    // 分页,每页显示 2 条

        return view('student.index', [
            'students' => $student
        ]);
    }

	// 添加页面 & 提交方法
    public function create(Request $request){
        // 提交到当前方法
        if($request->isMethod('POST')){
            $data = $request->input('Student');

            if(Student::create($data)){
                return redirect('student/index')->with('success', '添加成功');	// 闪存信息
            }else{
                return redirect()->back();
            }
        }

        return view('student.create');

    }
    
    // 提交到指定方法:action="{{ url('student/save') }}"
    // 保存添加
	public function save(Request $request){
        $data = $request->input('Student');

        // 获取模型
        $student = new Student();
        $student->name = $data['name'];
        $student->age = $data['age'];
        $student->gender = $data['gender'];

        if($student->save()){
            return redirect('student/index');
        }else{
            return redirect()->back();
        }
		
    } 

}
  • 修改 app/Student.php
<?php
// Model 里添加:设置批量赋值
protected $fillable = ['name', 'age', 'gender'];

  • routes/web.php 新建两条路由并修改
<?php
// 中间件使用 session,以及防止 xss 攻击
Route::group(['middleware' => ['web']], function(){
    Route::get('student/index', ['uses' => 'aaa@qq.com']);
    Route::any('student/create', ['uses' => 'aaa@qq.com']);
    Route::post('student/save', ['uses' => 'aaa@qq.com']);
});

  • 修改公共视图文件 resources/views/common/layouts.blade.php
  • 修改 “左侧菜单区域” 代码,添加链接
<!-- 左侧菜单区域,修改部分代码  -->
<div class="col-md-3">
    @section('leftmenu')
        <div class="list-group">
            <a href="{{ url('student/index') }}" class="list-group-item
            {{ Request::getPathInfo() != '/student/create' ? 'active' : ''}}
            ">学生列表</a>
            <a href="{{ url('student/create') }}" class="list-group-item
            {{ Request::getPathInfo() == '/student/create' ? 'active' : ''}}
            ">新增学生</a>
        </div>
    @show
</div>

  • 新建视图文件 resources/views/student/create.blade.php
@extends('common.layouts')

@section('content')

<!-- 自定义内容区域 -->
<div class="panel panel-default">
    <div class="panel-heading">新增学生</div>
    <div class="panel-body">
        <!-- 1. 提交到指定方法 -->
        <!-- <form class="form-horizontal" method="post" action="{{ url('student/save') }}"> -->
        <!-- 2. 提交到当前方法 -->
        <form class="form-horizontal" method="post" action="">

            <!-- 生成一个隐藏的 input 表单,带一个 token 字段 -->
            {{ csrf_field() }}
            <div class="form-group">
                <label for="name" class="col-sm-2 control-label">姓名</label>

                <div class="col-sm-5">
                    <input type="text" name="Student[name]" class="form-control" id="name" placeholder="请输入学生姓名">
                </div>
                <div class="col-sm-5">
                    <p class="form-control-static text-danger">姓名不能为空</p>
                </div>
            </div>
            <div class="form-group">
                <label for="age" class="col-sm-2 control-label">年龄</label>

                <div class="col-sm-5">
                    <input type="text" name="Student[age]" class="form-control" id="age" placeholder="请输入学生年龄">
                </div>
                <div class="col-sm-5">
                    <p class="form-control-static text-danger">年龄只能为整数</p>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">性别</label>

                <div class="col-sm-5">
                    <label class="radio-inline">
                        <input type="radio" name="Student[gender]" value="10"> 未知
                    </label>
                    <label class="radio-inline">
                        <input type="radio" name="Student[gender]" value="20"></label>
                    <label class="radio-inline">
                        <input type="radio" name="Student[gender]" value="30"></label>
                </div>
                <div class="col-sm-5">
                    <p class="form-control-static text-danger">请选择性别</p>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" class="btn btn-primary">提交</button>
                </div>
            </div>
        </form>
    </div>
</div>

@stop
  • 修改公共视图文件 resources/views/common/message.blade.php
 <!-- 成功提示框 -->
 @if (Session::has('success'))
 <div class="alert alert-success alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <strong>成功!</strong> {{ Session::get('success') }}
</div>
@endif

<!-- 失败提示框 -->
@if(Session::has('error'))
<div class="alert alert-danger alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <strong>失败!</strong>{{ Session::get('error') }}
</div>
@endif

4. 表单验证及数据保持;

  • 控制器验证

  • Validator 类验证

  • 数据保持

  • 修改 App/Http/Controllers/StudentController.php

  • 这次只修改了 create() 方法

// 添加页面 & 提交方法
    public function create(Request $request){
        // 提交到当前方法
         if($request->isMethod('POST')){
            /*
            // 1. 控制器验证
            // 如果验证通过了,代码会继续往下执行
            // 如果验证没通过,就会重定向到上一个页面,
            // 然后会抛出一个异常,并把错误信息存在 Session 中
            // 错误信息会分配到所有视图中,
            // 在视图中就可以获取到错误信息变量 $errors
            // $error 变量有一些方法可以回去到错误信息
            // 可以多错误信息进行自定义
            $this->validate($request, [
                'Student.name' => 'required|min:2|max:20',
                'Student.age' => 'required|integer',
                'Student.gender' => 'required|integer'
            ], [
                'required'  => ':attribute 为必填项',
                'min' => ':attribute 最少为两个字符',
                'max' => ':attribute 最多为二十个字符',
                'integer' => ':attribute 必须为整数'

                
            ], [
                'Student.name' => '姓名',
                'Student.age' => '年龄',
                'Student.gender' => '性别'
            ]); */

            // 2. Validator 类验证
            $validator = \Validator::make($request->input(), [
                'Student.name' => 'required|min:2|max:20',
                'Student.age' => 'required|integer',
                'Student.gender' => 'required|integer'
            ], [
                'required'  => ':attribute 为必填项',
                'min' => ':attribute 最少为两个字符',
                'max' => ':attribute 最多为二十个字符',
                'integer' => ':attribute 必须为整数'

                
            ], [
                'Student.name' => '姓名',
                'Student.age' => '年龄',
                'Student.gender' => '性别'
            ]);

            if($validator->fails()){
                // withErrors():手动注册错误信息,把 $validator 对象传入
                return redirect()->back()->withErrors($validator)->withInput();
            }


            $data = $request->input('Student');

            if(Student::create($data)){
                return redirect('student/index')->with('success', '添加成功');  // 闪存信息
            }else{
                return redirect()->back();
            }
        }

        return view('student.create');

    }
  • 新建公共视图文件 resources/views/common/validator.blade.php
<!-- 所有的错误提示 -->
@if(count($errors))
<!-- 取第一条错误 -->
<div class="alert alert-danger">
    <ul>
        <li>{{ $errors->first() }}</li>
    </ul>
</div>

<!-- 取所有错误 -->
<!-- <div class="alert alert-danger">
    <ul>
        @foreach($errors->all() as $error)
        <li>{{ $error }}</li>
        @endforeach
    </ul>
</div> -->
@endif
  • 在视图文件 resources/views/student/create.blade.php 中引入 resources/views/common/validator.blade.php,并对错误信息的显示、数据保持进行处理
@extends('common.layouts')

@section('content')

    @include('common.validator')

    <!-- 自定义内容区域 -->
    <div class="panel panel-default">
        <div class="panel-heading">新增学生</div>
        <div class="panel-body">
            <!-- 1. 提交到指定方法 -->
            <!-- <form class="form-horizontal" method="post" action="{{ url('student/save') }}"> -->
            <!-- 2. 提交到当前方法 -->
            <form class="form-horizontal" method="post" action="">

                <!-- 生成一个隐藏的 input 表单,带一个 token 字段 -->
                {{ csrf_field() }}
                <div class="form-group">
                    <label for="name" class="col-sm-2 control-label">姓名</label>

                    <div class="col-sm-5">
                        <input type="text" name="Student[name]" value="{{ old('Student')['name'] }}" class="form-control" id="name" placeholder="请输入学生姓名">
                    </div>
                    <div class="col-sm-5">
                        <p class="form-control-static text-danger">{{ $errors->first('Student.name') }}</p>
                    </div>
                </div>
                <div class="form-group">
                    <label for="age" class="col-sm-2 control-label">年龄</label>

                    <div class="col-sm-5">
                        <input type="text" name="Student[age]" value="{{ old('Student')['age'] }}" class="form-control" id="age" placeholder="请输入学生年龄">
                    </div>
                    <div class="col-sm-5">
                        <p class="form-control-static text-danger">{{ $errors->first('Student.age') }}</p>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">性别</label>

                    <div class="col-sm-5">
                        <label class="radio-inline">
                            <input type="radio" name="Student[gender]" value="10"> 未知
                        </label>
                        <label class="radio-inline">
                            <input type="radio" name="Student[gender]" value="20"></label>
                        <label class="radio-inline">
                            <input type="radio" name="Student[gender]" value="30"></label>
                    </div>
                    <div class="col-sm-5">
                        <p class="form-control-static text-danger">{{ $errors->first('Student.gender') }}</p>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-primary">提交</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

@stop

Laravel 表单

5. 通过模型处理单选框;

  • 修改模型 app/Student.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model{

    // 性别处理:定义三个常量
    const GENDER_UN = 10;       // 未知 
    const GENDER_MALE = 20;     // 男
    const GENDER_FEMALE = 30;   // 女

    // 指定表名
	protected $table = 'student';

	// 指定主键
    protected $primaryKey = 'id';

    // 设置批量赋值
    protected $fillable = ['name', 'age', 'gender'];

    // 自定义时间戳
    public $timestamps = true;

    public function getDateFormat(){
        return time();
    }

    protected function asDateTime($val){
        return $val;
    }


    // 性别处理
    public function getGender($ind = null){
        $arr = [
            self::GENDER_UN     => '未知',
            self::GENDER_MALE   => '男',
            self::GENDER_FEMALE => '女'
        ];

        if($ind != null){
            return array_key_exists($ind, $arr) ? $arr[$ind] : $arr[self::SEX_UN];
        }

        return $arr;
    }

}
  • 修改视图文件 resources/views/student/index.blade.php
 @extends('common.layouts')

 @section('content')

    <!-- 加载提示信息 -->
    @include('common.message')
        <!-- 自定义内容区域 -->
        <div class="panel panel-default">
            <div class="panel-heading">学生列表</div>
            <table class="table table-striped table-hover table-responsive">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>添加时间</th>
                    <th width="120">操作</th>
                </tr>
                </thead>
                <tbody>
                    <!-- 模型的方法可以通过模型对象去调用 -->
                    @foreach($students as $student)
                    <tr>
                        <th scope="row">{{ $student->id }}</th>
                        <td>{{ $student->name }}</td>
                        <td>{{ $student->age }}</td>
                        <td>{{ $student->getGender($student->gender) }}</td>
                        <td>{{ date('Y-m-d H:i:s', $student->created_at) }}</td>
                        <td>
                            <a href="">详情</a>
                            <a href="">修改</a>
                            <a href="">删除</a>
                        </td>
                    </tr>
                    @endforeach
                
                </tbody>
            </table>
        </div>

        <!-- 分页  -->
        <div>
            <div class="pull-right">
                {{ $students->render() }}
            </div>
        </div>

@stop
  • 修改 App/Http/Controllers/StudentController.php
  • 修改了 create() 方法
<?php
    // 添加页面 & 提交方法
    public function create(Request $request){

        $student = new Student();

        // 提交到当前方法
         if($request->isMethod('POST')){
            /*
            // 1. 控制器验证
            // 如果验证通过了,代码会继续往下执行
            // 如果验证没通过,就会重定向到上一个页面,
            // 然后会抛出一个异常,并把错误信息存在 Session 中
            // 错误信息会分配到所有视图中,
            // 在视图中就可以获取到错误信息变量 $errors
            // $error 变量有一些方法可以回去到错误信息
            // 可以多错误信息进行自定义
            $this->validate($request, [
                'Student.name' => 'required|min:2|max:20',
                'Student.age' => 'required|integer',
                'Student.gender' => 'required|integer'
            ], [
                'required'  => ':attribute 为必填项',
                'min' => ':attribute 最少为两个字符',
                'max' => ':attribute 最多为二十个字符',
                'integer' => ':attribute 必须为整数'

                
            ], [
                'Student.name' => '姓名',
                'Student.age' => '年龄',
                'Student.gender' => '性别'
            ]); */

            // 2. Validator 类验证
            $validator = \Validator::make($request->input(), [
                'Student.name' => 'required|min:2|max:20',
                'Student.age' => 'required|integer',
                'Student.gender' => 'required|integer'
            ], [
                'required'  => ':attribute 为必填项',
                'min' => ':attribute 最少为两个字符',
                'max' => ':attribute 最多为二十个字符',
                'integer' => ':attribute 必须为整数'

                
            ], [
                'Student.name' => '姓名',
                'Student.age' => '年龄',
                'Student.gender' => '性别'
            ]);

            if($validator->fails()){
                // withErrors():手动注册错误信息,把 $validator 对象传入
                return redirect()->back()->withErrors($validator)->withInput();
            }


            $data = $request->input('Student');

            if(Student::create($data)){
                return redirect('student/index')->with('success', '添加成功');  // 闪存信息
            }else{
                return redirect()->back();
            }
        }

        return view('student.create', [
            'student' => $student 
        ]);

    }
  • 修改视图文件 resources/views/student/create.blade.php
@extends('common.layouts')

@section('content')

    @include('common.validator')

    <!-- 自定义内容区域 -->
    <div class="panel panel-default">
        <div class="panel-heading">新增学生</div>
        <div class="panel-body">
            <!-- 1. 提交到指定方法 -->
            <!-- <form class="form-horizontal" method="post" action="{{ url('student/save') }}"> -->
            <!-- 2. 提交到当前方法 -->
            <form class="form-horizontal" method="post" action="">

                <!-- 生成一个隐藏的 input 表单,带一个 token 字段 -->
                {{ csrf_field() }}
                <div class="form-group">
                    <label for="name" class="col-sm-2 control-label">姓名</label>

                    <div class="col-sm-5">
                        <input type="text" name="Student[name]" value="{{ old('Student')['name'] }}" class="form-control" id="name" placeholder="请输入学生姓名">
                    </div>
                    <div class="col-sm-5">
                        <p class="form-control-static text-danger">{{ $errors->first('Student.name') }}</p>
                    </div>
                </div>
                <div class="form-group">
                    <label for="age" class="col-sm-2 control-label">年龄</label>

                    <div class="col-sm-5">
                        <input type="text" name="Student[age]" value="{{ old('Student')['age'] }}" class="form-control" id="age" placeholder="请输入学生年龄">
                    </div>
                    <div class="col-sm-5">
                        <p class="form-control-static text-danger">{{ $errors->first('Student.age') }}</p>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">性别</label>

                    <div class="col-sm-5">
                        @foreach($student->getGender() as $ind=>$val)
                        <label class="radio-inline">
                            <input type="radio" name="Student[gender]" value="{{ $ind }}">{{ $val }}
                        </label>
                        @endforeach
                    </div>
                    <div class="col-sm-5">
                        <p class="form-control-static text-danger">{{ $errors->first('Student.gender') }}</p>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-primary">提交</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

@stop

6. 通过表单实现修改;

  • 修改视图文件 resources/views/student/index.blade.php
<!-- 只需要添加修改按钮链接 -->
<td>
    <a href="">详情</a>
    <a href="{{ url('/student/update', ['id' => $student->id ]) }}">修改</a>
    <a href="">删除</a>
</td>
  • 修改 App/Http/Controllers/StudentController.php
// 新建一个方法
<?php
// 修改
public function update(Request $request, $id){
    $student = Student::find($id);

    if($request->isMethod('POST')){
        $this->validate($request, [
            'Student.name' => 'required|min:2|max:20',
            'Student.age' => 'required|integer',
            'Student.gender' => 'required|integer'
        ], [
            'required'  => ':attribute 为必填项',
            'min' => ':attribute 最少为两个字符',
            'max' => ':attribute 最多为二十个字符',
            'integer' => ':attribute 必须为整数'

            
        ], [
            'Student.name' => '姓名',
            'Student.age' => '年龄',
            'Student.gender' => '性别'
        ]); 

        $data = $request->input('Student');
        $student->name = $data['name'];
        $student->age = $data['age'];
        $student->gender = $data['gender'];

        if($student->save()){
            return redirect('student/index')->with('success', '修改成功 - '. $id);
        }
    }

    return view('student.update', [
        'student' => $student
    ]);
}
  • 修改视图文件 resources/views/student/update.blade.php
@extends('common.layouts')

@section('content')

    @include('common.validator')

    <!-- 自定义内容区域 -->
    <div class="panel panel-default">
        <div class="panel-heading">修改学生</div>
        <div class="panel-body">
        @include('student._form')
        </div>
    </div>

@stop
  • 由于新建学生和修改学生中的 form 表单是通用的,所以提取出来。新建视图文件 resources/views/student/_form.blade.php
<!-- 1. 提交到指定方法 -->
<!-- <form class="form-horizontal" method="post" action="{{ url('student/save') }}"> -->
<!-- 2. 提交到当前方法 -->
<form class="form-horizontal" method="post" action="">

    <!-- 生成一个隐藏的 input 表单,带一个 token 字段 -->
    {{ csrf_field() }}
    <div class="form-group">
        <label for="name" class="col-sm-2 control-label">姓名</label>

        <div class="col-sm-5">
            <input type="text" name="Student[name]" value="{{ old('Student')['name'] ? old('Student')['name'] : $student->name }}" 
            class="form-control" id="name" placeholder="请输入学生姓名">
        </div>
        <div class="col-sm-5">
            <p class="form-control-static text-danger">{{ $errors->first('Student.name') }}</p>
        </div>
    </div>
    <div class="form-group">
        <label for="age" class="col-sm-2 control-label">年龄</label>

        <div class="col-sm-5">
            <input type="text" name="Student[age]" value="{{ old('Student')['age'] ? old('Student')['age'] : $student->age }}" 
            class="form-control" id="age" placeholder="请输入学生年龄">
        </div>
        <div class="col-sm-5">
            <p class="form-control-static text-danger">{{ $errors->first('Student.age') }}</p>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label">性别</label>

        <div class="col-sm-5">
            @foreach($student->getGender() as $ind=>$val)
            <label class="radio-inline">
                <input type="radio" name="Student[gender]" 
                {{ isset($student->gender) && $student->gender == $ind ? 'checked' : '' }}
                value="{{ $ind }}">{{ $val }}
            </label>
            @endforeach
        </div>
        <div class="col-sm-5">
            <p class="form-control-static text-danger">{{ $errors->first('Student.gender') }}</p>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-primary">提交</button>
        </div>
    </div>
</form>
  • 修改视图文件 resources/views/student/create.blade.php
@extends('common.layouts')

@section('content')

    @include('common.validator')

    <!-- 自定义内容区域 -->
    <div class="panel panel-default">
        <div class="panel-heading">新增学生</div>
        <div class="panel-body">
            @include('student._form')
        </div>
    </div>

@stop
  • routes/web.php 新建一条路由
// 在 middleware 里新建一条路由
Route::any('student/update/{id}', ['uses' => 'aaa@qq.com']);
  • 修改模型 app/Student.php
// 添加如下方法
public function fromDateTime($val){
    return empty($val) ? $val : $this->getDateFormat();
}

7. 表单中查看详情及删除。

  • 修改视图文件 resources/views/student/index.blade.php
<!-- 只需要添加详情和删除按钮链接 -->
<td>
    <a href="{{ url('/student/detail', ['id' => $student->id ]) }}">详情</a>
    <a href="{{ url('/student/update', ['id' => $student->id ]) }}">修改</a>
    <a href="{{ url('/student/delete', ['id' => $student->id ]) }}" 
    onclick="if(confirm('确定删除?') == false) return false">删除</a>
</td>
  • 修改 App/Http/Controllers/StudentController.php
<?php
// 详情
public function detail($id){
    $student = Student::find($id);

    return view('student.detail', [
        'student' => $student
    ]);
}

// 删除
public function delete($id){
    $student = Student::find($id);

    if($student->delete()){
        return redirect('student/index')->with('success', '删除成功'. $id);
    }else{
        return redirect('student/index')->with('error', '删除失败'. $id);
    }
}
    
  • 新建视图文件 resources/views/student/detail.blade.php
@extends('common.layouts')

@section('content')
 <!-- 自定义内容区域 -->
 <div class="panel panel-default">
    <div class="panel-heading">学生详情</div>

    <table class="table table-bordered table-striped table-hover ">
        <tbody>
        <tr>
            <td width="50%">ID</td>
            <td>{{ $student->id }}</td>
        </tr>
        <tr>
            <td>姓名</td>
            <td>{{ $student->name }}</td>
        </tr>
        <tr>
            <td>年龄</td>
            <td>{{ $student->age }}</td>
        </tr>
        <tr>
            <td>性别</td>
            <td>{{ $student->getGender($student->gender) }}</td>
        </tr>
        <tr>
            <td>添加日期</td>
            <td>{{ date('Y-m-d', $student->create_at) }}</td>
        </tr>
        <tr>
            <td>最后修改</td>
            <td>{{ date('Y-m-d', $student->updated_at) }}</td>
        </tr>
        </tbody>
    </table>
</div>
@stop
  • routes/web.php 新建两条路由
// 在 middleware 里新建两条路由
Route::any('student/detail/{id}', ['uses' => 'aaa@qq.com']);
Route::any('student/delete/{id}', ['uses' => 'aaa@qq.com']);