How to use Raw MySQL queries in Laravel
How to use Raw MySQL queries in Laravel. Many developers have implementation problem with MySQL queries in Laravel and also, Laravel doesnot support the whole features of SQL queries. So we have one base function to use our Raw queries inside the function.
Which is even better for new developers and those who have problem with Laravel functions. By the way it protects the SQL injections and attacks through the following functions.
Let’s move to the function. and implementation example.
DB::insert(DB::raw('INSERT INTO `kvcodes` VALUES (12, 'varadhaa')'));
This is a simple function which will perform the insert operation. But here instead of the Laravel functions, i used to query the default raw query of MySQL.
Likewise, you can use it for Select, delete, update, and etc..
Here is an another example for Select Query:
$kv_id= Input::get("12"); $kv_results = DB::select( DB::raw("SELECT * FROM kvcodes WHERE id= '$kv_id'") );
This snippet will help you to get the results, with the help of the direct SQL query. And one more example query for Update .
DB::update(DB::raw('RENAME TABLE gallery TO medias'));
The above query rename the table from gallery to medias.
Another example for Delete operation:
$kv_id= Input::get("12"); DB::delete(DB::raw("DELETE FROM kvcodes_table WHERE id = '$kv_id'"));