Laravel在表单请求验证之后验证其他内容
在表单请求中进行常规验证之后,如何验证其他内容? 我需要根据输入中给定的名称验证文件夹是否存在Laravel在表单请求验证之后验证其他内容,laravel,validation,request,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.
<?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'
];
}
}
您可以使用自定义规则作为闭包,因此其他规则将是相同的
return [
'name' => ['required','between:1,64','string',function ($attribute, $value, $fail) {
if (file_exists(public_path('files/').$value)) {
$fail(':attribute directory already exists !');
}
}]
]
我希望您能理解。Laravel有一种机制,可以编写自定义规则进行验证。请看一看
此外,我建议使用存储对象来检查文件是否存在,这将是一个更方便、更健壮的解决方案。您可以参考以下官方文件:
您能指定要检查文件夹是否存在的位置吗?当然,我想检查文件夹是否存在:public/files/
我已经添加了我的答案,请尝试一下。效果很好。我不知道我可以在规则数组中添加这样的函数。谢谢@Kaizokupuffball很高兴知道它有效。你可以在这里看到规则的定制,
<?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.');
}
},
];
]
}
}