How to use Try catch to handle id variable error in Findorfail

Asked

Viewed 131 times

-2

public function finalizarCompra () {
  try {
    $compra = Compra::findOrFail($compra->id);
  }
  catch(ModelNotFoundException $e){
    return "erro";
  }    
}
  • What happens in this case? an Exception is launched?

  • 1

    can already solve my problem ! rray, I am beginner in programming I managed to solve now !

1 answer

2


Caleb,

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

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

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

    }
    catch(ModelNotFoundException $e){
        return "erro";
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.