How to validate Insert with relationship

Asked

Viewed 30 times

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

1 answer

0

You can use a Form Request customized.

// Para criar um `Form Request` execute o comando abaixo:
php artisan make:request CreateBrandRequest

Form Request:

class CreateBrandRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return auth()->check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'nome' => 'required|string|unique:marcas',
            'tipo_veiculo_id' => 'required|int|exists:tipos_veiculos',
        ];
    }
}

Controller:

public function create(CreateBrandRequest $request)
{
    $brand = Brand::create($request->all());
    // O método sync garante que não terá registros duplicados.
    $brand->typesVehicles()->sync([$request->input('tipo_veiculo_id')]);

    return response()->json(['message' => 'Tipo de veículo cadastrado com sucesso!'], 201);
}

Browser other questions tagged

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