美文网首页
Laravel使用表单请求验证

Laravel使用表单请求验证

作者: 老王谈编程 | 来源:发表于2017-11-23 10:46 被阅读0次

所有的表单验证都使用表单请求验证

  • 创建表单请求基类
$ php artisan make:request Request
  • 基类继承Request实例:app/Http/Requests/Request.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class Request extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
}
  • 创建学生表单请求
$ php artisan make:request StudentRequest
  • 修改StudentRequest:app/Http/Requests/StudentRequest.php
<?php

namespace App\Http\Requests;

class StudentRequest extends Request
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        switch($this->method())
        {
            // CREATE
            case 'POST':
                return [
                    'name' => 'required|min:1:max:10',
                    'age' => 'required|integer|between:1,120',
                    'sex' => 'required|integer|in:0,1,2'
                ];
                break;

            // UPDATE
            case 'PUT':
                break;

            case 'PATCH':
                return [
                    // UPDATE ROLES
                ];
                break;

            case 'GET':
                break;

            case 'DELETE':
                break;

            default:
                return [];
                break;
        }
    }

    public function messages()
    {
        return [

        ];
    }
}

  • 格式化参数中文名:resource/lang/en/validation.php
<?php

return [
    /*
    |--------------------------------------------------------------------------
    | Custom Validation Attributes
    |--------------------------------------------------------------------------
    |
    | The following language lines are used to swap attribute place-holders
    | with something more reader friendly such as E-Mail Address instead
    | of "email". This simply helps us make messages a little cleaner.
    |
    */

    'attributes' => [
        'name' => '姓名',
        'age' => '年龄',
        'sex' => '性别',
    ],

];

  • 控制器中使用请求验证,收工
<?php

namespace App\Http\Controllers;

use App\Http\Requests\StudentRequest;
use App\Models\Student;

class StudentsController extends BaseController
{
    public function store(StudentRequest $request)
    {
        Student::create($request->all());
        return redirect()->route('students.index')->with('success', '学生信息添加成功');
    }
}

相关文章

网友评论

      本文标题:Laravel使用表单请求验证

      本文链接:https://www.haomeiwen.com/subject/mvaavxtx.html