Is it mandatory to use the function DB::raw
when you are running a query and you are not using the fluent query builder in Laravel?
e.g.
$result = DB::select("SELECT * FROM users");
$result2 = DB::select(DB::raw("SELECT * FROM users"));
I get the same result in both cases. So why is it necessary to use DB::raw
?
DB::raw()
is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection.
Which means, using DB::raw()
only makes sense with a query builder (and it should be used with caution!).
While DB::select()
is not a query builder. And therefore it makes no sense to use DB::raw()
with DB::select()
.
As of models, there is no question whether to use it or not, because query builder's select()
method does not accept raw SQL strings and so DB::raw()
is required. Examples of using raw SQL with models.