Senario:
Problem:
If I add one title it validates the uniqeness under same category. Such:

But if I add multiple rows, validation does not work. Such:

I think foreach in 'CategoryResolverTitle' file is being exicuted once. What is the solution. My Form
<label for="Title">Title</label>
<input type="text" name="names[]" class="form-control">
My Custom Validator:
<?php
namespace App\Rules;
use App\Models\QueryManagement\CategoryResolver;
use Illuminate\Contracts\Validation\Rule;
class CategoryTitle implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
foreach ($value as $element) {
return !Category::whereDepartmentId(request('department'))->whereName($element)->exists();
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'Title under same category must be unique';
}
}
You current passes() function seems to be faulty. It will only start the loop once, then return the result of the first check immediately. A better way would be:
foreach ($value as $element) {
if(Category::whereDepartmentId(request('department'))->whereName($element)->exists()){
return false;
}
}
return true;
Asterisk symbol (*) is used to check values in the array, not the array itself.
$validator = Validator::make($request->all(), [
"names.*" => "required|string|distinct|min:3",
]);
In the example above:
EDIT: Since Laravel 5.5 you can call validate() method directly on Request object like so:
$data = $request->validate([
"name.*" => "required|string|distinct|min:3",
]);
also follow this url for more details
You can use array validation for this. There's a specific validation rule that can achieve database uniqueness:
$request->validate([
"names.*" => Rule::unique('categories', 'name')->where(function ($q) {
$q->where('department_id', request('department'));
})
]);