验证表单输入字段的正确方法

Right Way to validate form input fields

我正在构建一个 API,其中一个数据库 table Person 有 52 列,其中大部分是必需的 t 不要认为我正在做的事情是对的

public function store() {
    if (! input::get('name') or ! input::get('age') or ! input::get('phone') or ! input::get('address') and so on till the 52 field) {
        return "Unprocessable Entity";
    }

    return "Validated";
}

以及如何正确验证所有必填字段

谢谢

您可以简单地在请求文件中编写您的验证规则和消息,并可以直接在您的 store 函数中调用,如 as

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use Illuminate\Validation\Rule;

/**
 * Class YourFileRequest
 * @package App\Http\Requests
 */
class YourFileRequest extends Request
{

    /**
     * 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|unique:posts|max:255', 
           'body' => 'required',
        ];
    }

    /**
     * Get the custom validation messages that apply to the request.
     *
     * @return array
     */
    public function messages()
    {
        return [
           'title.required' => 'Please enter title', 
           'title.max' => 'Please enter max value upto 255', 
           'body.required' => 'Please enter body',
        ];
    }

}

在您的控制器中

use App\Http\Requests\YourFileRequest;


......


public function store(YourFileRequest $request) 
{
    //Your storing logic
}

您可以通过两种方式完成:

  1. 第一个是

    $this->validate($request,['email'=>'required|email|unique']);
    
  2. 其次,您可以使用以下命令创建一个单独的 ValidationRequest:

    php artisan make:request StoreRequest