0
I have three tables, one of the types of vehicles: car, motorcycle. A table of brands: Honda, Ferrari Another associative, called tag_type_vehicle.
The Honda brand for example, has cars and motorcycles. So it has two records in the table marca_tipo_veiculo, one for motorcycle, another for car.
I need to do a validation, which does not allow the brand name to duplicate in the table of brands, but it can be associated with more than one type of vehicle and this association can also be made only once for each type of vehicle, as the example of Honda.
I did so, but I believe it can be improved in a single validation:
public function create(Request $request)
{
$brand = Brand::where('nome', $request->nome);
if (!$brand->exists()) {
$request->validate([
'nome' => 'required|string|unique:marcas',
'tipo_veiculo_id' => 'required|int|exists:tipos_veiculos',
]);
$newBrand = Brand::create($request->all());
$newBrand->typesVehicles()->attach($request->tipo_veiculo_id);
return response()->json(['message' => 'Tipo de veículo cadastrado com sucesso!'], 201);
}
$brand = $brand->first();
/*
* valida que o id do tipo de veículo exista.
* valida a unicidade composta de marca e tipo de veículo.
*/
$request->validate([
'tipo_veiculo_id' =>
'exists:tipos_veiculos,id|unique:marca_tipo_veiculo,tipo_veiculo_id,NULL,id,marca_id,' . $brand->id
]);
$brand->typesVehicles()->attach($request->tipo_veiculo_id);
return response()->json(['message' => 'Tipo de veículo cadastrado com sucesso!'], 201);
}