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

sr57's avatar
Level 39

DB::raw vs DB::statement

I just noticed that DB::raw does not return any error, DB::statement (and other cdes) does.

There should be an explanation in the code, but I did not find any note about this in the documentation, neither in the web. Does sb have more information?

0 likes
7 replies
mabdullahsari's avatar

The former creates an in-memory Expression object which you can use in your queries whereas the latter immediately executes any statement/expression you pass along.

2 likes
sr57's avatar
Level 39

Thanks @mabdullahsari for the explanation, can you point me/us where this is explain in the doc and if the doc talks about the difference in exception handling?

sr57's avatar
Level 39

Thank @Sinnbeck for your reply.

Concerning exception, I don't thing it's a detail, it's not the first time I used raw query, but I was not aware of this before.

Nothing special with my code, it's just a (sql) view creation.

Having a look to the code, it's written that statement returns error, but it's not obvious (for me) that raw does not do it.

sr57's avatar
Level 39

@Sinnbeck You are (probably) right.

I really appreciate Laravel and its documentation.

In this particular case I should add a 2nd remember in bold "In addition of SQL injection vulnerability, be aware that raw expression does not throw exception.

And, personally, I'll replace all my "raw" by "statement"

jlrdw's avatar

You can still bind your parameters when using Raw. Then it's not raw.

Raw expression is good when eloquent doesn't have an equal.

1 like

Please or to participate in this conversation.