Follow the adapted solution following example above:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use App\Models\TypeVehicle;
class CheckTypeVehicleChildren implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$childrens = TypeVehicle::with('brands')->where($attribute, $value)->first();
return $childrens->brands()->count() > 0 ? false : true;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'Existem marcas associadas a este tipo de veículo';
}
}
Controller
public function delete(Request $request)
{
$request['id'] = $request->route('id');
$request->validate([
'id' => ['bail', 'required', 'int','exists:tipos_veiculos,id,deleted_at,NULL', new CheckTypeVehicleChildren()]
]);
$typeVehicle = TypeVehicle::find($request->id);
$typeVehicle->delete();
return response()->json(['message' => 'Tipo de veículo deletado com sucesso!'], 200);
}
You don’t think it’s better to create a foreign key between tables?
– gmsantos
The relationship is n para n in this case... In the table of marks I want to have a unique record, as I gave the example of the brand Honda, which can be both for car and bike. Or I’d have to create a composite key and duplicate the brand names
– João Paulo Silva