Check with session :: flash in Laravel

1

My question is about how to deal with this kind of errors.

So far I know that this happens because you can not delete a record that depends on another record of another table, which are related.

But my question is if you can show another kind of error, some message, or a different window to the common one when this kind of errors appear.

I was thinking of doing it with Session::flash() within the function destroy() of my controller, where I showed an error message, instead of going to that window. But I do not know how to do it very well. Thanks.

Additional information:

This way I have made the code where I try to set an error message.

public function destroy($id){

  try {

    $autos = AutosNew::find($id);

    $autos->delete();

    Session::flash('message', 'Automóvil eliminado correctamente del registro');
    return redirect()->back();

    } catch (Exception $e) {
        return "Fatal error -" .$e->getMessage(); 
  }
}

And if it fails the destroy() I would like to show an error message, instead of the error that shows the image I placed.

    
asked by M4uriXD 27.09.2018 в 23:27
source

1 answer

2

The problem is that you're not using try ... catch well, I think your code should look something like this:

public function destroy($id){

  $autos = AutosNew::find($id);

  try {

    $autos->delete();

  } catch (\Illuminate\Database\QueryException $e) {

    Session::flash('message', 'El automóvil no se pudo eliminar correctamente del registro');
    return redirect()->back_o_donde_sea();

  }

  Session::flash('message', 'Automóvil eliminado correctamente del registro');

  return redirect()->back();


}

Even if your code is in the "try" block, when the error occurs when trying to delete the record, the immediately following stops executing and the cursor jumps directly to the "catch" block; it is precisely there where you must decide what you will do with the error.

    
answered by 28.09.2018 / 19:41
source