Laravel在表单请求验证后验证其他内容

时间:2019-07-27 14:03:25

标签: laravel validation request

在表单请求中进行常规验证后,如何验证其他内容? 我需要根据输入中提供的名称来验证文件夹是否存在。

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CreateFolder extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return (auth()->check() && auth()->user()->can('create folders'));
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|between:1,64|string'
        ];
    }
}

在常规验证后,我验证文件夹是否存在时,我想使用相同的name。正如我所见,文档未指定任何有用的内容。

2 个答案:

答案 0 :(得分:1)

您可以使用自定义规则作为闭包,因此其他规则将相同。

return [
    'name' => ['required','between:1,64','string',function ($attribute, $value, $fail) {
        if (file_exists(public_path('files/').$value)) {
            $fail(':attribute directory already exists !');
        }
    }]
]

希望您能理解

答案 1 :(得分:0)

Laravel具有编写用于验证的自定义规则的机制。请看看https://laravel.com/docs/5.8/validation#custom-validation-rules

此外,我建议使用存储对象来检查文件是否存在,这将是一个更方便,更可靠的解决方案。可以参考https://laravel.com/docs/5.5/filesystem#retrieving-files

上的官方文档
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CreateFolder extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return (auth()->check() && auth()->user()->can('create folders'));
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => ['required', 
                       'between:1,64', 
                       'string',
                       function ($attribute, $value, $fail) {
                         if (!Storage::disk('local')->exists('file.jpg')) {
                           $fail($attribute.' does not exist.');
                         }
                       }, 
                      ];
       ]
    }
}