How to use try catch to handle the error of the variable id in FindOrFail [closed]

-2
public function finalizarCompra () {
  try {
    $compra = Compra::findOrFail($compra->id);
  }
  catch(ModelNotFoundException $e){
    return "erro";
  }    
}
    
asked by anonymous 11.03.2016 / 14:38

1 answer

2

Caleb,

If your function returns false you need to force an error with throw,

public function finalizarCompra () {
    try {
        $compra = Compra::findOrFail($compra->id);

        if (!$compra) {
            throw new Exception('Não encontrado');
        }

    }
    catch(ModelNotFoundException $e){
        return "erro";
    }
}
    
11.03.2016 / 21:10