我有以下数据模型:Region(id,name,countries_id,tag)。标签是唯一的,它由name + countries_id组成。例如:
name=Arizona
countries_id=us
tag=arizona-us
name和countries_id值附加在请求数据中,但标记值必须唯一且以dinamically方式生成。
我想创建一个验证规则来验证标记值的唯一性属性。
我的代码是:
return array(
'name' => ['required', new RegionUniqueRule()],
'countries_id' => ['required', 'exists:mysql.countries,id'],
);
class Regionunique implements Rule
{
public function passes($attribute, $value)
{
$countriesIdValue = 'COUNTRIES_ID VALUE !!!';
$text = sprintf('%s %s', $value, $countriesIdValue);
$table = DB::table('regions');
$table->where('tag', str_slug($text));
return ($table->first() === null);
}
public function message()
{
return 'The region already exists';
}
}
那么,我如何才能获得Regionunique中的countries_id值?
答案 0 :(得分:0)
您可以做的是在验证之前创建输入,如下所示:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest
{
/**
* Override Symfony\Component\HttpFoundation\Request::initialize.
* After parent::initialize, run beforeValidation
*/
public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
parent::initialize($query, $request, $attributes, $cookies, $files, $server, $content);
$this->beforeValidation();
}
protected function beforeValidation()
{
//implement in child class
}
}
class MyRequest extends Request
{
protected function beforeValidation()
{
$tag = sprintf('%s %s', $this->input('name'), $this->input('countries_id'));
$this->merge([
'tag' => $tag,
]);
}
public function rules()
{
return array(
'name' => ['required'],
'countries_id' => ['required', 'exists:mysql.countries,id'],
'tag' => ['required','unique'],
);
}
}
class MyController
{
public function myMethod(MyRequest $request)
{
//do something
}
}
这里我们创建一个新的Request抽象类,它覆盖框架中的initialize(..)
函数。初始化后,基类调用beforeValidation()
以在验证之前运行任何内容。然后我们在输入数组中插入一个新的输入值tag
,并根据unique
规则进行验证。