Laravel 表單驗證器的幾種使用方法

cosyphp發表於2020-07-15

1、使用控制器的 validate 方法進行引數驗證

/**
 * 儲存一篇新的部落格文章。
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // 文章內容是符合規則的,存入資料庫
}

2、手動建立驗證器例項進行驗證

  • 使用預設的驗證資訊
/**
 * 儲存一篇新的部落格文章。
 *
 * @param  Request  $request
 * @return Response
 */
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();
    }

    // 文章內容是符合規則的,存入資料庫
}
  • 使用自定義的驗證資訊
/**
 * 儲存一篇新的部落格文章。
 *
 * @param  Request  $request
 * @return Response
 */
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
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|max:20',
            'name'  => ['required', new Uppercase()],
        ];
    }

    /**
     * 獲取已定義的驗證規則的錯誤訊息。
     *
     * @return array
     */
    public function messages()
    {
        return [
            'title.required' => 'A title is required',
            'title.max'  => 'The title may not be greater than 20 characters.',
        ];
    }

    /**
     * 相容 form 表單請求與 ajax 請求或者 json api 請求
     * 驗證失敗,返回錯誤資訊
     *
     * @param Validator $validator
     * @throws
     */
    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);
        }
    }
}
  • 在控制器中使用 ExampleRequest
<?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 協議》,轉載必須註明作者和本文連結

cosyphp

相關文章