Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

227
Visualizações
Input Array is not being validated if it contains more than one value in laravel custom validation

Senario:

  • Title under each category will be unique.
  • I want to write a custom validator which cheks if same title with category exists.

Problem:

If I add one title it validates the uniqeness under same category. Such: It is working

But if I add multiple rows, validation does not work. Such: enter image description here

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';
    }
}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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;
over 4 years ago · Santiago Trujillo Relatório

0

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:

  • "names" must be an array with at least 3 elements,
  • values in the "names" array must be distinct (unique) strings, at least 3 characters long.

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

over 4 years ago · Santiago Trujillo Relatório

0

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'));
    })
]);

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda