Laravel 8 手動(dòng)創(chuàng)建驗(yàn)證器

2021-07-17 16:08 更新

如果您不想再請(qǐng)求中使用 validate 方法,您可以使用 Validator 門面 手動(dòng)創(chuàng)建一個(gè)驗(yàn)證器實(shí)例。門面中的 make 方法將會(huì)生成一個(gè)新的驗(yàn)證器實(shí)例:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{
    /**
     * 存儲(chǔ)一篇博客文章
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                        ->withErrors($validator)
                        ->withInput();
        }

        // Store the blog post...
    }
}

make 方法中的第一個(gè)參數(shù)是期望校驗(yàn)的數(shù)據(jù)。第二個(gè)參數(shù)是應(yīng)用到數(shù)據(jù)上的校驗(yàn)規(guī)則。

如果校驗(yàn)失敗,您可以使用 withErrors 方法將錯(cuò)誤信息閃存至 session 中。使用該方法時(shí), $errors 會(huì)自動(dòng)與之后的視圖共享,您可以很方便將其回顯給用戶。withErrors 方法接受驗(yàn)證器實(shí)例, MessageBag 或是 PHP 數(shù)組


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)