Crashman
Crashman

Reputation: 146

Laravel, unique columns

I need validate if field already exist, throws error, but with this code no errors are triggered

Laravel 7

table: departamento
column: id int incremental
column: departamento varchar(150)
column: idPais       int

store method

$this->validate($request, ['departamento' => Rule::unique('departamento','idPais')->where('departamento',$request->depto)->where('idPais',$request->pais)]);

Try with this too

 $rules = [
'depto' => [Rule::unique('departamento')->where(function ($query) use ($request) {
    return $query->where('departamento','=', $request->depto)->where('idPais','=', $request->pais);
}),]
];
 $this->validate($request,$rules);

with this code, throws this error

 $rules = [
'depto' => [Rule::unique('departamento')->where(function ($query) use ($request) {
    return $query->where('departamento','=', $request->depto)->where('idPais','=', $request->pais);
}),]
];
$this->validate($request,$rules);

error

Thanks!!!

EDIT:

My bad, I need check two fields , departamento and idPais, thanks.

Upvotes: 0

Views: 331

Answers (1)

Pirvu2k
Pirvu2k

Reputation: 151

This is happening because of your field name. The unique rule will try to find a record with that column name set to the request value (in your case, depto, but your column name is departamento). When you are customising the query you are not overriding it, you are adding on top of this default behaviour. From the laravel docs:

By default, the unique rule will check the uniqueness of the column matching the name of the attribute being validated. However, you may pass a different column name as the second argument to the unique method:

With that in mind, you could either change the unique rule to set the column to departamento and not depto as per below, or change the request to send departamento attribute instead of depto:

$rules = [
'depto' => [Rule::unique('departamento', 'departamento')->where(function ($query) use ($request) {
    return $query->where('idPais','=', $request->pais);
}),]
];

Upvotes: 1

Related Questions