Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

thesimons's avatar

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".

try {
            if ($user->save()) {
				return response()->json(true);
            } else {
                return response()->json(false);
            }
        } catch (\Exception $e) {
            return response()->json(false);
        }

for some reasons the the query retuned an error because of a missing field but the script retuned a true result.

So my question is: in Laravel isn't necessary to check each query?

Thanks, Simone

0 likes
6 replies
tisuchi's avatar

@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
}
thesimons's avatar

@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.

Thanks, Simone

tykus's avatar

it looks like that even if the SQL query fails it returns "true"

Eloquent's save method does not exhibit that behaviour. What else is going on in your app with regard to error handling?

thesimons's avatar

@tykus Ok, it explains the issue. I'm at my first approaches with Laravel coming from 24 years of coding in core php.

Snapey's avatar

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

thesimons's avatar

@Snapey Yes, I'm slowly learning. It's like start driving with automatic shift after 24 years of manual one LOL

Please or to participate in this conversation.