【问题标题】:Laravel validating something else after form-request validationLaravel 在表单请求验证后验证其他内容
【发布时间】:2023-03-22 08:41:01
【问题描述】:

如何在表单请求中的常规验证之后验证其他内容? 我需要根据输入中给出的名称验证文件夹是否存在。

<?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。正如我所见,文档没有指定任何有用的东西。

【问题讨论】:

  • 能否指定要检查文件夹是否存在的位置?
  • 好的,我想检查文件夹是否存在:public/files/
  • 我已经添加了我的答案,请尝试一下。

标签: laravel validation request


【解决方案1】:

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

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

希望你能理解。

【讨论】:

【解决方案2】:

Laravel 有一种机制可以编写自定义规则进行验证。请看https://laravel.com/docs/5.8/validation#custom-validation-rules

此外,我建议使用 Storage 对象来检查文件是否存在,这将是一种更方便、更强大的解决方案。可以参考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.');
                         }
                       }, 
                      ];
       ]
    }
}

【讨论】:

    猜你喜欢
    • 2016-09-02
    • 2016-05-23
    • 2016-03-11
    • 2015-06-09
    • 1970-01-01
    • 2016-08-10
    • 2018-02-11
    • 2020-12-11
    相关资源
    最近更新 更多