Problem with validation 'Unique' in Laravel

Asked

Viewed 280 times

-1

Hello, I’m starting to learn Laravel, I’m doing a small project and I’m in the validation part, but I’m having problems with validation when I want to validate a unique value (Unique).

class Categoria extends Model {

public $timestamps = false;

public function frases() {
    return $this->belongsToMany('App\Frase');
}

public function validar($request) {
    $mensagens = [
        'nome.required' => 'O campo nome é obrigatório!',
        'nome.max' => 'O limite de caracteres do campo nome foi excedido!',
        'descricao.required' => 'O campo descricao é obrigatório!',
        'descricao.max' => 'O limite de caracteres do campo descricao foi excedido!',
        'tipo.required' => 'O campo tipo é obrigatório!',
        'slug.required' => 'O campo slug é obrigatório!',
        'slug.max' => 'O limite de caracteres do campo slug foi excedido!',
        'slug.unique' => 'O slug ja existe',
    ];

    $validator = Validator::make($request->all(), [
        'nome' => 'required|max:40',
        'descricao' => 'required|max:150',
        'tipo' => 'required',
        'slug' => 'required|max:40|unique:categorias',
    ], $mensagens);

    return $validator;}
}

Well, as you can see the validation actually works, but when I edit a category it ends up saying that the value of Slug already exists, I wonder what is the best way to create an exception if you are the owner of the Slug that is being edited...

Thanks for now :)

1 answer

2

I have solved the problem, I will leave it to those who are facing the same problem. In the validation part I include the id indication of the register to be modified, this way he understands that Unique does not apply to this register, since he is the owner of the same...

$validator = Validator::make($request->all(), [
        'nome' => 'required|max:40',
        'descricao' => 'required|max:150',
        'tipo' => 'required',
        'slug' => 'required|max:40|unique:categorias,slug,'.$request->id //essa linha
    ], $mensagens);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.