Those two examples yield the same result, although with different result data types.
Using raw queries can indeed be an attack vector if you don't escape values used within the query (especially those coming from user input).
However that can be mitigated very easily by using bindings passed as the second parameter of any raw query method, as showcased in the same documentation (selectRaw
accepts a second parameter as an array of bindings, as well as other raw methods from the Query Builder such as whereRaw
, etc). Actually at the begining of the docs page you referenced, the second paragraph also states the following:
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
So as long as you're careful and make sure any parameters are passed as bindings and not concatenated as plain values within the raw query string you should be safe.
DB::select
already accepts a raw SQL query string, so the innerDB::raw
in the second example is unnecessary, and will actually screw up things like query logging. – Reinaldoreinaldos