hello I have a table called gallery_category_contents
language | title | gallery_category_id |
---|---|---|
en | FISH | 1 |
en | DOGS | 2 |
and my request rules are like this
public function rules()
{
return [
"language"=>[
"required",
Rule::unique('gallery_category_contents','language')->ignore($this->gallery_category_id,'gallery_category_id')
],
"title"=>[
"string",
"required"
]
];
}
what i want is that it doesn't add already existing language with same gallery_category_id
For example, English language has been added to 1 gallery_category_id, so it should not be added again. my current code works, but it affects all the data in that table, that is, it also affects category 2
how to do it?
CodePudding user response:
Please try this way:
public function rules(): array
{
return [
'gallery_category_id' => [
'required',
Rule::exists('gallery_category'),
],
'language' => [
'required',
Rule::unique('gallery_category_contents', 'language')
->where('gallery_category_id', $this->input('gallery_category_id')),
],
'title' => [
'required',
'string',
]
];
}
CodePudding user response:
You could make your own validation rule:
php artisan make:rule CompositeUnique
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class CompositeUnique implements Rule, DataAwareRule
{
private array $data;
private array $columns;
private $model;
private $ignoreId;
/**
* Create a new rule instance.
*
* @param $model
* @param string|array $colums
* @return void
*/
public function __construct($model, $columns, $ignoreId)
{
$this->model = $model;
$this->columns = (array)$columns;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return $this->model::query()
->where($this->columns, array_reduce(function($where, $column) {
$where[$column] = $this->data[$column];
return $where;
}, [])
->where($this->model->getKeyName(), $this->ignoreId)
->doesntExist();
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The :attribute must be unique.';
}
/**
* Set the data under validation.
*
* @param array $data
* @return $this
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
}
And use it like this:
use App\Rules\CompositeUnique;
use App\Models\GalleryCategoryContents;
//...
new CompositeUnique(
GalleryCategoryContents::class,
[ 'language' 'gallery_category_id' ],
$this->gallery_category_id
);`