Problem with 'unique' validation in Laravel

-1

Hello, I'm starting to learn Laravel, I'm doing a small project and I'm in the validations part, however I'm having problems with validation when I want to validate a unique value.

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 does work, but when I edit a category it ends up saying that the value of the slug already exists, I would like to know how best to create an exception if it is the owner of the slug that is being edited ...

Thanks for the time being:)

    
asked by anonymous 16.06.2018 / 02:06

1 answer

2

I was able to solve the problem, I'll leave it to those who are facing the same problem. In the part of the validation I include the indication of the id of the register to be modified, in this way he understands that unique does not apply to this register, since he owns it ...

$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);
    
16.06.2018 / 02:19