Validate Laravel Referential Integrity 5

0

In laravel 5.1, is there any way to validate the referential integrity of the data?

I explain. I have 2 tables related by an FK Where Country can have several Departments (or States), how can I validate when a user wants to delete a Country that already has related Departments, show the user a message that indicates why it can not, instead of that the system sends the DELETE to the database and this generates the error of Foreign Key

SQLSTATE [23000]: Integrity constraint violation: 1451 Can not delete or update a parent row: a foreign key constraint fails ( sisoft . departamento , CONSTRAINT FK_Pais_idPais_departamento FOREIGN KEY ( Pais_idPais ) REFERENCES pais ( idPais ) ON DELETE NO ACTION ON UPDATE NO ACTION) (SQL: delete from pais where idPais = 1)

    
asked by Andres Sierra 19.08.2016 в 16:49
source

1 answer

2

In the destroy method of your PaisController you can do something similar to the following:

public function destroy(Pais $pais)
{
    if(count($pais->departamentos)){
        return // La vista que quieras en caso de que no se pueda borrar
    }
    Pais::destroy($pais->id);
    return // La vista que quieras tras borrar el país
}

Simply verify that the country to be eliminated does not have associated departments (through a relationship established in your models with the departamentos() method), and if you have them send the user where you want, telling them that they can not be deleted.

    
answered by 20.08.2016 / 16:47
source