我有3个参数(br_code,slc_code,slt_code) 我已完成 br_code 和 slc_code 的验证
为了验证 slt_code,我必须检查 slc_code 和 slt_code 是否存在于表(sltype)上,我该怎么做?
谢谢你
首先,创建自定义验证规则。您可以通过使用您自己的规则扩展 Validator 类来实现此目的。我们称这条规则为
ExistInTable
。
php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;
class ExistInTable implements Rule
{
protected $table;
protected $column;
public function __construct($table, $column)
{
$this->table = $table;
$this->column = $column;
}
public function passes($attribute, $value)
{
return DB::table($this->table)
->where($this->column, $value)
->exists();
}
public function message()
{
return 'The selected :attribute does not exist in the specified table.';
}
}
现在,您可以在验证逻辑中使用此自定义规则。以下是将其合并到 Laravel 验证规则中的方法:
use App\Rules\ExistInTable;
$request->validate([
'br_code' => 'required',
'slc_code' => 'required',
'slt_code' => [
'required',
new ExistInTable('sltype', 'slc_code'),
new ExistInTable('sltype', 'slt_code'),
],
]);
请告诉我这是否能解决您的问题。