Difference Between Laravel Source SQL Functions

I don't seem to be the only person struggling with the differences between the Laravel DB :: raw (), DB :: select (), DB :: statement () and DB :: unprepared () methods. It almost seems like you should try the SQL job with all 4 to determine what will work. Can someone explain how they relate to each other and which ones to use for what purposes?

+5
source share
1 answer

I will try to clarify:

DB :: raw ()

It generates a raw and sanitized SQL string that is passed to other queries / statements, preventing SQL injections. Used with everyone and never alone. And you should never send a non-sanitized string to your inquiries / operators.

DB::select(DB::raw('select * from whatever')); 

DB :: select ()

Used for simple selection:

 DB::select(DB::raw('select * from whatever')); 

DB :: operator ()

I think it works with selects, but should be used for non-SQL query commands:

 DB::statement(DB::raw('update whatever set valid = true;')); 

DB :: unprepared ()

All SQL commands in Laravel are prepared by default, but sometimes you need to run the command in unprepared mode, since some commands in some database cannot be run in prepared mode. Here's the problem I discovered about this: https://github.com/laravel/framework/issues/53

 DB::unprepared(DB::raw('update whatever set valid = true;')); 
+12
source

Source: https://habr.com/ru/post/1200505/


All Articles