Laravel 验证在两列上是唯一的

下面是我的表的结构:

公司

  • ID

  • uuid

  • 公司名称

公司分支机构

  • ID

  • corp_id

  • 分店名称

这种关系被定义为每个公司可以有许多 corp_branches 但我想检查每个公司下的 branch_name 是否应该是唯一的。不同公司下的两个不同分支机构可以同名,但一个公司下的两个分支机构不能同名。

我试过这个

'branch_name' => 'required|string|max:100|unique:corp_branches,branch_name,NULL,id,corp_id,'.$this->get('corp_id'),



元芳怎么了
浏览 127回答 2
2回答

犯罪嫌疑人X

'branch_name' =>['required', 'unique:corp_branches,corp_id,'.$this->id.',NULL,corp_id,branch_name,'.$request->input('branch_name')]

慕虎7371278

&nbsp; &nbsp; 您需要自定义验证规则。步骤 #1 - 生成规则php artisan make:rule UniqueBranch步骤 #2 - 修改app/Rules/UniqueBranch.php<?phpnamespace App\Rules;use Illuminate\Contracts\Validation\Rule;class UniqueBranch implements Rule{&nbsp; &nbsp; protected $corp_id;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Create a new rule instance.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @return void&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function __construct($corp_id)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->corp_id = $corp_id;&nbsp; &nbsp; }&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Determine if the validation rule passes.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @param&nbsp; string&nbsp; $attribute&nbsp; &nbsp; &nbsp;* @param&nbsp; mixed&nbsp; $value&nbsp; &nbsp; &nbsp;* @return bool&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function passes($attribute, $value)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Assume your model name is `Corporation`&nbsp; &nbsp; &nbsp; &nbsp; $corporation = Corporation::find($this->corp_id);&nbsp; &nbsp; &nbsp; &nbsp; if ($corporation) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $exists = $corporation&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ->corp_branches() // assume you have relation to braches&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ->where('name', $value)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ->count();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!$exists) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Get the validation error message.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @return string&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function message()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return 'The branch name has already been taken.';&nbsp; &nbsp; }}步骤 #3 - 使用UniqueBranch'branch_name' => [&nbsp; &nbsp; 'required',&nbsp; &nbsp; 'string',&nbsp; &nbsp; 'max:100',&nbsp; &nbsp; new UniqueBranch($this->get('corp_id'))]
打开App,查看更多内容
随时随地看视频慕课网APP