所有的表单验证都使用表单请求验证
$ 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', '学生信息添加成功');
}
}