Try / catch no needed with Laravel on database operations?
Hello,
when I used to code in core php I was a bit paranoid about handling possible errors of a sql query.
So I used try / catch and if a lot. Today I tried to do the same with Laravel however it looks like that even if the SQL query fails it returns "true".
@thesimons If I understand you correctly, in Laravel, you don't need to use try/catch for every database operation unless you want to handle specific exceptions.
You can simply try this:
try {
$user->save(); // Will throw an exception if it fails
return response()->json(true); // Return true if save is successful
} catch (\Exception $e) {
// Optionally log the exception or handle specific types of exceptions
return response()->json(false); // Return false if an error occurs
}
@tisuchi Thanks for your reply. My question was mainly about the "efficacy" of using try/catch. I had a clear SQL error because of a missing filed in the database but the try/catch (exactly like your example) returned a true value.
The first time that came up in my mind was that Laravel, having its own debugging system, override in some way the error that triggers the try/catch.
The difference here is that laravel will throw an exception if there is an error. The return value can be ignored.
Only catch the error if you think there is something you can do to recover the situation. Otherwise you can let the error occur and the framework will look after logging and reporting