Show notice when trying to delete foreign key LARAVEL

1

I have two tables with one to many relationship, "Locations" and "Devices", the problem arises when trying to delete a "location" that has a "device" related, I need you to show a notice that says that the deletion was not made and not the error SQLSTATE [23000], is it possible to capture the error? this is what I have so far.

public function destroy(Location $location)
{
    try {
        //Eliminar registro
        $location->delete();
    } catch (Illuminate\Database\QueryException $e) {
        $status = 'Registro relacionado, imposible de eliminar';
    }
    //Retornar vista
    return redirect()->route('locations.index')
        ->with('status', $status);
}
    
asked by Setkn 08.11.2018 в 12:42
source

2 answers

1

I think that catch is not working for you, you would not have the forward slash. Would you stay:

catch (\Illuminate\Database\QueryException $e)

A shorter alternative would be:

catch (\Exception $e) 

Of rest, everything equal.

    
answered by 08.11.2018 / 13:19
source
0

You should check if there are records in the related tables, for this you can use the Eloquent relationships, I assume you have created them.

It should be something like this:

public function destroy(Location $location)
{
    $status='';
    $count=0;

    // Contamos los registros en las relaciones
    $count+=count($location->tabla1);
    $count+=count($location->tabla2);
    // Comprobamos si existen registros 
    if($count>0) {
        $status =  'Existen registros relacionados';
    } else {
        // si no hay registros eliminamos
        $location->delete();
        $status =  'Eliminado correctamente';
    }

    return redirect()->route('locations.index')
        ->with('status', $status);
}
    
answered by 08.11.2018 в 13:24