phplaravellaravel-5.4

laravel try/catch doesn't work for a failed query


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 ?


Solution

  • When using a class from one namespace in another namespace, you have to provide a full qualified namespace, either using use statemen ot right in the call. For example you should use catch ( \Throwable $e ) to catch any exception.

    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 ( \Throwable $e )
    {
        $form->error_flag = 6 ;
        $form->save();
    }