How to execute a multiple raw query using laravel?

by cali_green , in category: PHP Frameworks , a year ago

How to execute a multiple raw query using laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , a year ago

@cali_green 

To execute multiple raw queries in Laravel, you can make use of the DB facade and its statement method.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use IlluminateSupportFacadesDB;

// Define your raw queries
$queries = [
    "INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]')",
    "UPDATE users SET name = 'Jane Doe' WHERE id = 1",
    "DELETE FROM users WHERE id = 2"
];

// Execute the queries
foreach ($queries as $query) {
    DB::statement($query);
}


In the above example, we have defined three raw queries in an array. Then, we iterate over the array and execute each query using the DB::statement() method.


Make sure to import the DB facade at the top of your file with use IlluminateSupportFacadesDB;.