Laravel 8 手動創(chuàng)建驗證器

2021-07-17 16:08 更新

如果您不想再請求中使用 validate 方法,您可以使用 Validator 門面 手動創(chuàng)建一個驗證器實例。門面中的 make 方法將會生成一個新的驗證器實例:

<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * 存儲一篇博客文章
     *
     * @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 方法中的第一個參數(shù)是期望校驗的數(shù)據(jù)。第二個參數(shù)是應用到數(shù)據(jù)上的校驗規(guī)則。

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


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號