1、使用控制器的 validate
方法進行引數驗證
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
}
2、手動建立驗證器例項進行驗證
public function store(Request $request)
{
$rules = [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return redirect('post/create')->withErrors($validator)->withInput();
}
}
public function store(Request $request)
{
$rules = [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
$messages = [
'title.required' => '請填寫文章標題',
'title.unique' => '文章標題不能重複',
'title.max' => '文章標題不能超過255個字元',
'body.required' => '請填寫文章內容',
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return redirect('post/create')->withErrors($validator)->withInput();
}
}
3、建立表單請求進行驗證
- 建立表單請求檔案:
php artisan make:request ExampleRequest
- 表單請求檔案內容:
<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
class ExampleRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required|max:20',
'name' => ['required', new Uppercase()],
];
}
public function messages()
{
return [
'title.required' => 'A title is required',
'title.max' => 'The title may not be greater than 20 characters.',
];
}
protected function failedValidation(Validator $validator)
{
if ($this->wantsJson() || $this->ajax()) {
throw new HttpResponseException(
new JsonResponse([
'code' => 500,
'msg' => $validator->errors()->first(),
'data' => new \stdClass()
])
);
} else {
parent::failedValidation($validator);
}
}
}
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\ExampleRequest;
class ExampleController extends Controller
{
public function valid(ExampleRequest $request)
{
$params = $request->all();
dd($params);
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結