Laravel transactions with a database
Overall, you've got decent structure there. However, there are a few things I can see from my limited experience.



You defined an associative array $data at the beginning. From experience, it usually works best to define it fully up front instead of in bits and pieces. This is not required in PHP like it is in Java, but it usually works better because it keeps your code looking clean and organized. It's hard to know what exactly is in your array if you add to it in multiple places.

From what I can see, you don't have any specific delimiters or checks to see if the inputs exist, this should be the first thing you do. If something is null, there should be red flags going up.

That being said, inside the try statement you insert into the database twice. Both times you pass $data to the insertGetId() magic method. While you do want to pass an associative array, you must make sure that all required fields are in that array. Effectively, you're duplicating your data with just an extra column.

Reading your $data array, you have a column named 'till_account_id'. If I understand the project correctly, this field should be unique as no one person should share an account. There may be cosigners, but it isn't technically their account. That being said, I think the 'till_account_id' should be your primary key, which means your insert should look like this:

DB::table('till_transaction')-&gt;insertGetId($data,'till_account_id');




Be very careful when you return data. You return several variables defined inside of an if statement. If the update fails, it will return null which means !empty($update) will fail because you're trying to read a null object. The same goes for further down, when you return, all the values that were defined inside the if statement wouldn't exist, thus returning null.



Good job catching the exception and then rethrowing it to the caller. Most people would catch it and forget to handle it. That being said, though, depending on how specific of an app you're developing, it might be beneficial to make a custom exception class and do something like this:

catch (Exception $e) {
    //respond here as needed
    throw new CustomException('some message describing error',0,$e);
}


This would do whatever you need to do, then rethrow the exception in a more manageable fashion. You would have a message specific to what you need to explain - details are very important in debugging, you would have the error code, and you would have the previous exception passed to the new exception for the trace.