Eloquent is the answer for all kinds of database operations in Laravel. As a matter of fact, which is a great solution for interacting with databases. But if we have complicated business logic/ complex MySQL queries, oftentimes we need to write raw queries in Laravel.
A key concern about the usage of raw queries in Laravel is SQL injection. In the first place, we have Laravel’s query builder to protect us from harmful minds. But if we intentionally opened the door for malicious hands, Laravel has nothing to do.
For example, consider the below query
$yourVar = Input::get("some_variable_from_a_form"); $results = DB::select( DB::raw("SELECT * FROM your_table WHERE your_col = '$yourVar'") );
In the above query, we directly input the form value into our query without sanitizing. This is a dangerous practice and should avoid by all means.
Although this may work, you should use the Laravel way as shown in the below example. In this case, bindings are the perfect tool to avoid SQL injection.
$yourVar = Input::get("some_variable_from_a_form"); $results = DB::select( DB::raw("SELECT * FROM your_table WHERE your_col = :yourVar"), array( 'yourVar' => $yourVar, ));
Before we finish the article, I have to remind you something.
Do not use the select method if your query is performing some execution that does not return results. For example, altering a column of a table. Use the statement method to perform a query execution.
DB::statement( 'ALTER TABLE your_Table CHANGE `data` `data` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL' );
Hope it was an informative article, don’t hesitate to share it with your peers.
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
nice