i have a INSERT query which might fail due to certain unique key in database so im using try/catch to avoid the error ...btw form_id is unique 
    try {
        $reward = new UserCreditForm();
        $reward->user_id = $form->user_id ;
        $reward->form_id = $form->id ;
        $reward->amount = $amount ;
        $reward->result = $result ;
        $reward->save();
        $form->result = $result ;
        $form->save();
    }
    catch ( Exception $e )
    {
        $form->error_flag = 6 ;
        $form->save();
    }
but try/catch doesnt workwhen uniqu key fails and i get
Whoops, looks like something went wrong.
(2/2) QueryException
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'user_credit_forms_form_id_unique' (SQL: insert into `user_credit_forms` (`user_id`, `form_id`, `amount`, `result`, `updated_at`, `created_at`) values (2, 1, 499392, 1, 2017-08-31 14:45:06, 2017-08-31 14:45:06))
is there anyway to avoide the error and jump on the catche part if query fails ?
You should use catch ( \Exception $e ) to catch all exceptions in try.
Final form should look like this:
try {
    $reward = new UserCreditForm();
    $reward->user_id = $form->user_id ;
    $reward->form_id = $form->id ;
    $reward->amount = $amount ;
    $reward->result = $result ;
    $reward->save();
    $form->result = $result ;
    $form->save();
}
catch ( \Exception $e )
{
    $form->error_flag = 6 ;
    $form->save();
}
                        Way 1:
You need to use
\Illuminate\Database\QueryException $e
in your catch
} catch (\Illuminate\Database\QueryException $e) {
Reference for QueryException
Way 2:
You can alternatively use:
} catch (\Exception $e) {
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With